2011年10月18日 星期二

Perl ->Avoid Symbolic References

Perl Style: Avoid Symbolic References

  • Beginners often think they want to have a variable contain the name of a variable.
    $fred    = 23;
        $varname = "fred";
        ++$$varname;         # $fred now 24
  • This works sometimes, but is a bad idea. They only work on global variables. Global variables are bad because they can easily collide accidentally.
  • They do not work under the use strict pragma
  • They are not true references and consequently are not reference counted or garbage collected.
  • Use a hash or a real reference instead.

Forward to Using A Hash Instead of $$name
Back to Avoid Byte Processing
Up to index
Copyright © 1998, Tom Christiansen
All rights reserved.







#symbolicRef.pl


$var    = 23;
$varnameref = "var";
++$$varnameref;         # $fred now 24
print $var,"\n";




@arr  =(1..10);
$arrnameref = "arr";
print @$arrnameref,"\n";


%hash = (
  k1 => "v1",
  k2 => "v2",
);


$hashnameref = "hash";
print %$hashnameref;


#輸出結果

24
12345678910
k2v2k1v1

沒有留言:

張貼留言