Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What’s the best way to discover all variables a Perl application has currently defined?

I am looking for best, easiest way to do something like:

$var1="value";
bunch of code.....
**print allVariablesAndTheirValuesCurrentlyDefined;**
like image 404
Ville M Avatar asked Apr 09 '09 18:04

Ville M


People also ask

How do you check a variable is defined in Perl?

Perl | defined() FunctionDefined() in Perl returns true if the provided variable 'VAR' has a value other than the undef value, or it checks the value of $_ if VAR is not specified. This can be used with many functions to detect for the failure of operation since they return undef if there was a problem.

What does @_ mean in Perl?

@ is used for an array. In a subroutine or when you call a function in Perl, you may pass the parameter list. In that case, @_ is can be used to pass the parameter list to the function: sub Average{ # Get total number of arguments passed. $ n = scalar(@_); $sum = 0; foreach $item (@_){ # foreach is like for loop...

What is $_ in Perl?

The most commonly used special variable is $_, which contains the default input and pattern-searching string. For example, in the following lines − #!/usr/bin/perl foreach ('hickory','dickory','doc') { print $_; print "\n"; }

What does $@ meaning in Perl?

The variables are shown ordered by the "distance" between the subsystem which reported the error and the Perl process...$@ is set if the string to be eval-ed did not compile (this may happen if open or close were imported with bad prototypes), or if Perl code executed during evaluation die()d.


2 Answers

Package variables? Lexical variables?

Package variables can be looked up via the symbol table. Try Devel::Symdump:

#!/path/to/perl

use Devel::Symdump;

package example;

$var = "value";
@var = ("value1", "value2");
%var = ("key1" => "value1", "key2" => "value2");

my $obj = Devel::Symdump->new('example');

print $obj->as_string();

Lexical variables are a little tricker, you won't find them in the symbol table. They can be looked up via the 'scratchpad' that belongs to the block of code they're defined in. Try PadWalker:

#!/path/to/perl

use strict;
use warnings;

use Data::Dumper;
use PadWalker qw(peek_my);

my $var = "value";
my @var = ("value1", "value2");
my %var = ("key1" =>  "value1", "key2" => "value2");

my $hash_ref = peek_my(0);

print Dumper($hash_ref);
like image 186
Mark Johnson Avatar answered Feb 07 '23 01:02

Mark Johnson


The global symbol table is %main::, so you can get global variables from there. However, each entry is a typeglob which can hold multiple values, e.g., $x, @x, %x, etc, so you need to check for each data type. You can find code that does this here. The comments on that page might help you find other solutions for non-global variables (like lexical variables declared with "my").

like image 27
Nathan Kitchen Avatar answered Feb 07 '23 02:02

Nathan Kitchen