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:
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.my $foo = "example"; foreach my $bar ($foo) { # Right now $foo and $bar are the same }
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:
but that would probably be a bad idea.foreach my $var_name (qw(foo bar baz)) { $hash{$var_name} = eval "\$$var_name"; }
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.
In reply to Re: getting the name of a variable to use as string
by tilly
in thread getting the name of a variable to use as string
by pmneve
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |