Wednesday, March 10, 2010

Use local instead of my in Perl when using $$ (double dollar sign) inside an enclosed block

I thought I would be all clever and initialize several hash indices at once using the $$ notation in Perl - evaluating strings as variables. Unfortunately using "my" screws this up bigtime.

This must be another circumstance spelled out in the incomprehensible "my" treatise:
http://perldoc.perl.org/perlsub.html#Private-Variables-via-my()


my %foo;
$foo{'bar'}=1;
foreach $fooDex(qw(foo)){
$$fooDex{'bar'}=2;
}
print $foo{'bar'}."\n"; #prints 1




local %foo;
$foo{'bar'}=1;
foreach $fooDex(qw(foo)){
$$fooDex{'bar'}=2;
}
print $foo{'bar'}."\n"; #prints 2


This is one of those solutions that gives you a feeling of dread instead of accomplishment.

No comments:

Post a Comment