<?xml version="1.0" encoding="windows-1252"?>
<node id="807126" title="Re: Can you find the name of a variable?" created="2009-11-14 05:57:09" updated="2009-11-14 05:57:09">
<type id="11">
note</type>
<author id="747201">
afoken</author>
<data>
<field name="doctext">
&lt;p&gt;If you want to know the name of a variable, you usually try to do something stupid. Most times, the answer is to use a hash instead. Also in this case, you can use a hash to get named parameters instead of positional parameters.&lt;/p&gt;
&lt;p&gt;Something like this:&lt;/p&gt;
&lt;code&gt;
sub blah
{
    my %args=(@_);
    foreach my $needed (qw( foo bar baz )) {
        exists $args{$needed} or die "blah() needs a $needed parameter";
    }
    # ....
}

blah(foo =&gt; 42, bar =&gt; "don't forget this", baz =&gt; 'oh!');
blah(foo =&gt; 42, baz =&gt; 'oh!'); # &lt;-- will die()
&lt;/code&gt;
&lt;p&gt;Back to the "what's the name of the variable problem". What should a hypothetical &lt;c&gt;nameThatVariable()&lt;/c&gt; function return for the following cases?&lt;/p&gt;
&lt;code&gt;
$foo=42;
print nameThatVariable($foo); # '$foo', of course.

$foo=[ 42 ];
print nameThatVariable($foo); # still '$foo'.

@bar=( 42 );
print nameThatVariable(@bar); # '@bar', of course.

$baz=$foo=\@bar;
print nameThatVariable($foo); # 'reference to @bar' or '$foo'?
print nameThatVariable($baz); # 'reference to @bar' or '$foo' or '$baz' ?

print nameThatVariable(\@bar); # 'reference to @bar'?

print nameThatVariable(do { my $tmp=23 }); # '$tmp'?

print nameThatVariable([ 23,45 ]); # ?
&lt;/code&gt;
&lt;p&gt;Alexander&lt;/p&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-747201"&gt;
--&lt;br&gt;
Today I will gladly share my knowledge and experience, for there are no sweeter words than "I told you so". ;-)
&lt;/div&gt;&lt;/div&gt;</field>
<field name="root_node">
807025</field>
<field name="parent_node">
807025</field>
</data>
</node>
