Kelly Jones wrote:
> Inside a subroutine, I want to use this hash:
> 
> %hash = ("apple" => "red", "pear" => "green", "[EMAIL PROTECTED]" => 
> "yellow");

So just use the hash.

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

Just use the hash.

> 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'}");
> }

You can clean up the hash keys like so:

%hash = map { ( my $key = $_ ) =~ s/[^a-z_]//ig; $key, $hash{ $_ } } keys %hash;

Or like so:

for ( keys %hash ) {
    ( my $key = $_ ) =~ s/[^a-z_]//ig;
    $hash{ $key } = delete $hash{ $_ };
    }

> 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.

So just use the hash.

> 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?

Just use the hash.



John
-- 
Perl isn't a toolbox, but a small machine shop where you can special-order
certain sorts of tools at low cost and in short order.       -- Larry Wall

-- 
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