Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get variable name as string in Perl

Tags:

variables

perl

I am trying to get a text representation of a variable's name. For instance, this would be the function I am looking for:

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

I want this because I am trying to write a debug function that recursively outputs the contents of a passed variable. I want it to output the variable's name before hand so if I call this debug function 100 times in succession, there will be no confusion as to which variable I am looking at in the output.

I have heard of Data::Dumper and am not a fan. If someone can tell me how to if it's possible get a string of a variable's name, that would be great.

like image 656
Jose Cuervo Avatar asked Mar 04 '11 22:03

Jose Cuervo


People also ask

What is @_ and $_ in Perl?

$_ - The default input and pattern-searching space. @_ - Within a subroutine the array @_ contains the parameters passed to that subroutine. $" - When an array or an array slice is interpolated into a double-quoted string or a similar context such as /.../ , its elements are separated by this value.

What is$@ in Perl?

$@ The Perl syntax error or routine error message from the last eval, do-FILE, or require command. If set, either the compilation failed, or the die function was executed within the code of the eval.

How do I print a variable in Perl script?

In any real-world Perl script you'll need to print the value of your Perl variables. To print a variable as part of a a string, just use the Perl printing syntax as shown in this example: $name = 'Alvin'; print "Hello, world, from $name.

How do I concatenate a string and a variable in Perl?

In general, the string concatenation in Perl is very simple by using the string operator such as dot operator (.) To perform the concatenation of two operands which are declared as variables which means joining the two variables containing string to one single string using this concatenation string dot operator (.)


1 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
like image 80
toolic Avatar answered Oct 07 '22 09:10

toolic