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.


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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.