Get variable name as string in Perl

I am trying to get a textual representation of a variable name. For example, this will be the function I'm looking for:

$abc = '123'; $var_name = &get_var_name($abc); #returns '$abc' 

I need this because I'm trying to write a debug function that recursively displays the contents of the passed variable, I want it to output the variable name before hand, so if I call this debug function 100 times in a row, there will be no confusion as to which variable I am looking for a way out.

I heard about Data :: Dumper and am not a fan. If someone can tell me how to do this, if it is possible to get a string of the variable name, that would be great.

Thanks!

+8
variables perl
source share
3 answers

Data :: Dumper :: Simple

 use warnings; use strict; use Data::Dumper::Simple; my $abc = '123'; my ($var_name) = split /=/, Dumper($abc); print $var_name, "\n"; __END__ $abc 
+8
source share

To do this, you need to use the PadWalker module, which allows you to check lexical panels that store variables.

 use PadWalker qw/peek_my peek_our/; sub debug { my $my = peek_my 1; my $our = peek_our 1; my $caller = caller() . '::'; my $stash = do { no strict 'refs'; \%$caller }; my %lookup; for my $pad ($my, $our) { $lookup{$$pad{$_}} ||= $_ for keys %$pad; } for my $name (keys %$stash) { if (ref \$$stash{$name} eq 'GLOB') { for (['$' => 'SCALAR'], ['@' => 'ARRAY'], ['%' => 'HASH'], ['&' => 'CODE']) { if (my $ref = *{$$stash{$name}}{$$_[1]}) { $lookup{$ref} ||= $$_[0] . $caller . $name } } } } for (@_) { my $name = $lookup{\$_} || 'name not found'; print "$name: $_\n"; } } 

and then use it:

 my $x = 5; our $y = 10; $main::z = 15; debug $x, $y, $main::z; 

which prints:

 $x: 5 $y: 10 $main::z: 15 

EDIT:

Here is the same functionality, the bit has been reorganized:

 use PadWalker qw/peek_my peek_our/; sub get_name_my { my $pad = peek_my($_[0] + 1); for (keys %$pad) { return $_ if $$pad{$_} == \$_[1] } } sub get_name_our { my $pad = peek_our($_[0] + 1); for (keys %$pad) { return $_ if $$pad{$_} == \$_[1] } } sub get_name_stash { my $caller = caller($_[0]) . '::'; my $stash = do { no strict 'refs'; \%$caller }; my %lookup; for my $name (keys %$stash) { if (ref \$$stash{$name} eq 'GLOB') { for (['$' => 'SCALAR'], ['@' => 'ARRAY'], ['%' => 'HASH'], ['&' => 'CODE']) { if (my $ref = *{$$stash{$name}}{$$_[1]}) { $lookup{$ref} ||= $$_[0] . $caller . $name } } } } $lookup{\$_[1]} } sub get_name { unshift @_, @_ == 2 ? 1 + shift : 1; &get_name_my or &get_name_our or &get_name_stash } sub debug { for (@_) { my $name = get_name(1, $_) || 'name not found'; print "$name: $_\n"; } } 
+6
source share

My (lexical) variable names are erased, so you cannot get their names. Package variable names are accessible by writing to the symbol table ( *var ), as described in another article.

-2
source share

All Articles