Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Inspecting the name of a variable

by LanX (Canon)
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

Comment on Inspecting the name of a variable
Download Code
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

        Hello

        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".

        update:
        Sorry if I am looking into wrong direction.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://991185]
Approved by tye
Front-paged by Haarg
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (11)
As of 2014-09-16 07:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (157 votes), past polls