Inside a subroutine, I want to use this hash:

%hash = ("apple" => "red", "pear" => "green", "[EMAIL PROTECTED]" => "yellow");

to set my($apple)="red", my($pear)="green", my($lemon)="yellow"
[getting rid of the junk '@' and '!' chars in the key]

This is approximately what PHP's extract() does. This almost works:

for $i (keys %hash) {
 $safe = $i; # keep safe copy of $i
 $i=~s/[^a-z_]//isg; # get rid of nonalpha characters in key
 unless ($i=~/^[a-z_]+$/) {next;} # if key is now empty, ignore it
 eval("\$$i = \$hash{'$safe'}");
}

but the assignments are made in the global namespace, not just in the
subroutine namespace. Replacing the eval with:

eval("my(\$$i) = \$hash{'$safe'}");

doesn't work either, because the my() is now local to the eval, and
doesn't set variables in the subroutine namespace.

I don't know the hash keys ahead of time, so I can't hardcode:

my($apple,$pear,$lemon);

Of course, variables in the global namespace are available in the
subroutine namespace, so the first version is usable, but dangerous
(could clobber existing global variables). Thoughts?

--
We're just a Bunch Of Regular Guys, a collective group that's trying
to understand and assimilate technology. We feel that resistance to
new ideas and technology is unwise and ultimately futile.
-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>

Reply via email to