How can I list all variables that are in a given scope?

And that does it. Thanks to MGoDave and kbosak for providing the answer in front of my face that I was too stupid to see (I looked in %main:: to start with, but missed that they didn't have their sigils). Here is the complete code:

#!/usr/bin/perl

use strict;
use warnings;

use PadWalker qw/peek_our peek_my/;
use Data::Dumper;

our $foo = 1;
our $bar = 2;

{
    my $foo = 3;
    print Dumper in_scope_variables();
}

print Dumper in_scope_variables();

sub in_scope_variables {
    my %in_scope = %{peek_our(1)};
    my $lexical  = peek_my(1);
    for my $name (keys %main::) {
        my $glob = $main::{$name};
        if (defined ${$glob}) {
            $in_scope{'$' . $name} = ${$glob};
        }

        if (defined @{$glob}) {
            $in_scope{'@' . $name} = [@{$glob}];
        }

        if (defined %{$glob}) {
            $in_scope{'%' . $name} = {%{$glob}};
        }
    }

    #lexicals hide package variables
    while (my ($var, $ref) = each %$lexical) {
        $in_scope{$var} = $ref;
    }
    return \%in_scope;
}

You can do something like the following to check the symbol table of the main package:

{
    no strict 'refs';

    for my $var (keys %{'main::'}) {
        print "$var\n";
    }
}

You can access the symbol table, check out p. 293 of "Programming Perl" Also look at "Mastering Perl: http://www252.pair.com/comdog/mastering_perl/ Specifically: http://www252.pair.com/comdog/mastering_perl/Chapters/08.symbol_tables.html

Those variables you are looking for will be under the main namespace

A quick Google search gave me:

{
    no strict 'refs';

    foreach my $entry ( keys %main:: )
    {
        print "$entry\n";
    }
}

You can also do

*sym = $main::{"/"}

and likewise for other values

If you want to find the type of the symbol you can do (from mastering perl):

foreach my $entry ( keys %main:: )
{
    print "-" x 30, "Name: $entry\n";

    print "\tscalar is defined\n" if defined ${$entry};
    print "\tarray  is defined\n" if defined @{$entry};
    print "\thash   is defined\n" if defined %{$entry};
    print "\tsub    is defined\n" if defined &{$entry};
}

Tags:

Perl