Perl stash output

Viewed 144

I am trying to run a code snippet from the Advanced Perl Programming book for dumping the stash. This is without any additional packages from CPAN.

The package containing the stash related instructions is as follows:

package DUMPVAR;

sub dumpvar {
    my ($packageName) = @_;

    local (*alias);
    *stash = *{"${packageName}::"};

    $, = " ";

    while (($varName, $globValue) = each %stash) {

        print "\n $varName ===========================================\n";
        *alias = $globValue;

        if (defined ($alias)) {
            print "\t \$$varName $alias \n";
        }
        if (@alias) {
            print "\t \@$varName @alias \n";
        }
        if (keys %alias) {
            print "\t \%$varName " , %alias, " \n";
        }
    };
};
1;

The calling code is

#!/usr/bin/perl
use strict;
use warnings;

use DUMPVAR;

package MyData;

my $x = 10;
my @y = (1,2,3);
my %z = (1,2,3,4,5,6);
my $z = 300;

DUMPVAR::dumpvar('MyData');

I get no output what so ever. what is the problem?

2 Answers

You don't see anything because you've only defined lexical variables. Those aren't tracked in the package system. Get rid of my (and strict because you haven't declared things, and warnings because you only use things once):

package MyData;

$x = 10;
@y = (1,2,3);
%z = (1,2,3,4,5,6);
$z = 300;

Dumpvar::dumpvar('MyData');

The output is:

 y ===========================================
     @y 1 2 3

 x ===========================================
     $x 10

 z ===========================================
     $z 300
     %z  3 4 5 6 1 2

Lexical Variables defined with my are not stored in the package.

You have to either declare them with "our" (instead of my), or don't declare them at all and add

use vars qw($x @y %z $z);

to add them to the package.

Related