You can't.
The internal reason is that the exact same scalar may have multiple names by which it can be accessed at the same time. For instance in the following code the exact same variable is $foo and $bar:
my $foo = "example";
foreach my $bar ($foo) {
# Right now $foo and $bar are the same
}
There is no general way to know which one you'd want back, so Perl doesn't even think of trying to answer that question.
Instead you'll need to step back and think about the problem that you're trying to solve and then solve it in a different way. My feeling is that you're working too hard to avoid a simple line of code. But if you really feel strongly about it, you can achieve the effect with something like this:
foreach my $var_name (qw(foo bar baz)) {
$hash{$var_name} = eval "\$$var_name";
}
but that would probably be a bad idea.
UPDATE: Thinking about it I had the awful idea that someone actually might be able to write a function that stares at the optree for the caller and figures out what the passed in variable was called (in simple cases). This would be an even worse idea than the eval in my books. |