I'll also assume that you won't be dealing with people changing packages. Otherwise, you'll have to navigate around all possible packages and keep track of an initial state.
Oh, and string eval, security risk, blah, blah.
Lastly, this solution will fail if a scalar actually holds an undef. This is because *{$glob}{SCALAR} will always return a reference to a scalar regardless of whether you ever actually accessed that scalar. The docs say "[t]his might change in a future release."
I give you my modified version of your code:
#use strict; use warnings; use Term::ReadLine; my $prompt = "prompt> "; my $prog = Term::ReadLine->new('Script'); $prog->ornaments(0); while (defined (my $cmd = $prog->readline($prompt))) { chomp $cmd; # nothing if ($cmd =~ /^\s*$/) { next } # exit if ($cmd =~ /^\s*exit\s*$/) { last } # execute eval "package Sandbox; $cmd"; warn $@ if $@; print "\n" } package Sandbox; sub command { print "Special command"; } sub names { my @keys = sort keys %Sandbox::; for my $key (@keys) { my $glob = \*{"Sandbox::$key"}; print "\$$key\n" if defined ${*{$glob}{SCALAR}}; print "\@$key\n" if defined *{$glob}{ARRAY}; print "\%$key\n" if defined *{$glob}{HASH}; } }
Outside of the addition of the names routine, you'll note I've added package statements to your eval and the subroutine declarations. This avoids the problem of your dump being polluted by the very large number of special variables in the main package.
This approach also has the advantage of only outputting names associated with actual variables, as well as telling the user what variable type they were. Just dumping the names from the table will also yield all subroutines in the package, which is probably not what you mean. You could even add a subroutine to print out all available subroutines:
sub commands { my @keys = sort keys %Sandbox::; for my $key (@keys) { my $glob = \*{"Sandbox::$key"}; print "\&$key\n" if defined *{$glob}{CODE}; } }
Reference materials to be found in Symbol Tables from perlmod and in perlref.
#11929 First ask yourself `How would I do this without a computer?' Then have the computer do it the same way.
In reply to Re: Print variable name/value for all program variables
by kennethk
in thread [SOLVED] - Print variable name/value for all program variables
by VinsWorldcom
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |