In the chapter “Symbol Tables and Typeglobs”, I show some tricks to look at the symbol table to see which variables are there. I ended the chapter with a short example of Package::Stash, but in updating an answer to the Stackoverflow questions [How can I list all variables that are in a given scope?](https://stackoverflow.com/a/79771517/2766176), I came up with a better example, and one that does a better job of handling variable names that
use v5.12;
package Local {
my $package = 'Local::';
our $foo;
our @bar;
}
vars_in( 'main' );
vars_in( 'Local' );
sub vars_in {
state $rc = require Package::Stash;
my( $package ) = @_;
my $stash = Package::Stash->new($package);
my @list = $stash->list_all_symbols;
say $package;
foreach my $symbol ( sort @list ) {
next if $symbol =~ /::\z/;
(my $printable_symbol = $symbol) =~ s/([\x00-\x1F\x7F])/control_char_to_str($1)/ge;
say " $printable_symbol";
foreach my $sigil ( qw($ @ % &), '' ) {
my $var = "$sigil$symbol";
(my $printable_var = $var) =~ s/([\x00-\x1F\x7F])/control_char_to_str($1)/ge;
say " has $printable_var" if $stash->has_symbol($var);
}
}
}
sub control_char_to_str {
my $char = shift;
my $ord = ord($char);
return '^?' if $ord == 127; # DEL
return '^' . chr($ord + 64);
}