S
Stefano Sabatini
Hi perl guys,
I would like to import an hash in a lexycal scope, so to be able
to access the values of the hash as they were lexicals variables
defined in the current lexycal scope.
For example I would like to define somewhere an hash like:
my %hash = (one => 1, two => 2, three => 3, four => 4);
and then be able to access the variables $one, $two, $three after
importing them:
{
# import the hash
...
print "One is $one, two is $two, three is $three and so on";
}
I successfully achieved to import an hash into the current package using
this incantation:
foreach (keys %hash) {
*$_ = \$hash{$_};
}
I also tried this:
{
my $keys_str;
foreach (keys %hash) { $keys_str.= "\$$_, " };
# here it evals the code in the evalled code lexycal environment, which is
# (unfortunately) not the current lexycal environment, so the
# lexycal binding is immediately discarded
eval "my ($keys_str)";
no strict;
# this cause the creation of global (package) variables
# and don't warn 'cause of the no strict pragma
foreach (keys %hash) {
eval "\$$_ = $hash{$_};";
}
}
but after some debugging and thinkering I realized it can't work (as
explained in the comments above).
So I'm thinking maybe it's not possible at all to achieve my goal, or
maybe I can't simply see how.
Any help or suggestion will be highly appreciated.
Many cheers
I would like to import an hash in a lexycal scope, so to be able
to access the values of the hash as they were lexicals variables
defined in the current lexycal scope.
For example I would like to define somewhere an hash like:
my %hash = (one => 1, two => 2, three => 3, four => 4);
and then be able to access the variables $one, $two, $three after
importing them:
{
# import the hash
...
print "One is $one, two is $two, three is $three and so on";
}
I successfully achieved to import an hash into the current package using
this incantation:
foreach (keys %hash) {
*$_ = \$hash{$_};
}
I also tried this:
{
my $keys_str;
foreach (keys %hash) { $keys_str.= "\$$_, " };
# here it evals the code in the evalled code lexycal environment, which is
# (unfortunately) not the current lexycal environment, so the
# lexycal binding is immediately discarded
eval "my ($keys_str)";
no strict;
# this cause the creation of global (package) variables
# and don't warn 'cause of the no strict pragma
foreach (keys %hash) {
eval "\$$_ = $hash{$_};";
}
}
but after some debugging and thinkering I realized it can't work (as
explained in the comments above).
So I'm thinking maybe it's not possible at all to achieve my goal, or
maybe I can't simply see how.
Any help or suggestion will be highly appreciated.
Many cheers