Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer

Inspecting the name of a variable

by LanX (Bishop)
on Sep 01, 2012 at 19:19 UTC ( #991185=perlquestion: print w/replies, xml ) Need Help??
LanX has asked for the wisdom of the Perl Monks concerning the following question:

Hei Friends

is there any better way to find the "our" name of a package variable other than searching thru all possibilities?

And why can't I find $x? cause its an alias?

use feature qw(say); use PadWalker qw(var_name peek_our); use Data::Dump qw(pp); sub our_name { my $varref=\shift; my $h_our=peek_our(1); while ( my ($name,$ref) = each %$h_our ) { return $name if $ref == $varref; } return; } package test; our $bar=10; package main; for our $x (1) { say our_name($bar); # > $bar say our_name($x); # > '' }

Cheers Rolf

Replies are listed 'Best First'.
Re: Inspecting the name of a variable
by philiprbrenan (Monk) on Sep 01, 2012 at 19:49 UTC

    From the manual entry for 'for':

    Foreach Loops

    The foreach loop iterates over a normal list value and sets the variable VAR to be each element of the list in turn. If the variable is preceded with the keyword my, then it is lexically scoped, and is therefore visible only within the loop. Otherwise, the variable is implicitly local to the loop and regains its former value upon exiting the loop. If the variable was previously declared with my, it uses that variable instead of the global one, but it's still localized to the loop. This implicit localization occurs only in a foreach loop

      Well ... RTFM doesn't explain anything. =)

      localized variables are propagated into any called subs.

      apparently PadWalker is missing a pad to investigate or should extend it's documentation.

      UPDATE: ... well only if aliases have a pad...

      UPDATE: yes it's because of the aliasing:

      our $orig=666; for our $x (42,$orig) { say $bar,our_name($bar); say $x,our_name($x); }

      10$bar 42 10$bar 666$orig

      Cheers Rolf


        I found Data::Dumper::Names with this thread . In this manual of Data::Dumper::Names, there is "Unknown Variables" section.

        "Unknown Variables" section seems to me having some relation with your case... not printing name "$x".

        Sorry if I am looking into wrong direction.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://991185]
Approved by tye
Front-paged by Haarg
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (2)
As of 2018-07-23 04:28 GMT
Find Nodes?
    Voting Booth?
    It has been suggested to rename Perl 6 in order to boost its marketing potential. Which name would you prefer?

    Results (459 votes). Check out past polls.