tphyahoo has asked for the wisdom of the Perl Monks concerning the following question:

O wise monks, I have a script, test.pl, that calls a module test.pm.

In test.pl, I can make calls to Data::Dumper, a handy thing for dumping data structures like arrays of hashes, hashes of arrays, and so on.

But when I make calls to Data::Dumper inside test.pm, I get undefined function errors.

Can someone please help me get back on the path to perl enlightenment?

The script.....

#test.pl use warnings; use strict; use Data::Dumper; use lib 'E:/data/entwicklungsArena/perl/development/modules'; use Misc::Test ('test_function'); my $test = "Test"; print Dumper($test); #works, prints $VAR1='Test'; test_function; #fails, "undefined subroutine &Misc::Test::Dumper....."

And the module.....

#test.pm use strict; use warnings; use Data::Dumper; package Misc::Test; use base 'Exporter'; our @EXPORT_OK = ('test_function'); my $test = "test"; sub test_function { print Dumper($test); }
Thanks!

Replies are listed 'Best First'.
Re: how to use Data::Dumper inside a module?
by Tanktalus (Canon) on Feb 11, 2005 at 15:22 UTC

    Rule of thumb: "package" declarations should go at the top of your module. Yes, they don't have to, but that's an advanced topic for when you know what you're doing ;-) I may consider myself advanced, but I still always put the (first) package statement as the very very first line in a module.

      Yes! That worked! Thanks Tanktalus!
Re: how to use Data::Dumper inside a module?
by Fletch (Bishop) on Feb 11, 2005 at 15:37 UTC

    And as for why it didn't work, look at this output:

    $ cat Spoo.pm print "pre package: ", __PACKAGE__, "\n"; package Spoo; print "post package: ", __PACKAGE__, "\n"; 1; $ perl -MSpoo -e 0 pre package: main post package: Spoo

    In your code your use Data::Dumper line (which is implicitly running Data::Dumper->import()) is being executed in the main package. When you subsequently try and use Dumper() Perl sees an unqualified sub name (since it didn't get imported into Misc::Test) and gripes.

Re: how to use Data::Dumper inside a module?
by naChoZ (Curate) on Feb 11, 2005 at 18:54 UTC

    You might find this useful. Kanji gave me this little sample snippet that he wrote:

    package My::Debug; use base Exporter; use Data::Dumper 'Dumper'; our $DEBUG_LEVEL = 0; our @EXPORT = qw( debug debug_level ); sub debug { return unless $DEBUG_LEVEL; my($pre_msg, $var, $post_msg) = @_; no warnings; print join( "\n", "", $pre_msg, "<" x 20, Dumper($var), ">" x 20, $post_msg, "" ); } sub debug_level { $DEBUG_LEVEL = shift; } 1;

    Elsewhere...

    use My::Debug; debug_level( $opt_v ); sub foo_sub { ... code ... debug('begin showing foovar', $foovar, 'end of foovar'); ... code ... }

    --
    "This alcoholism thing, I think it's just clever propaganda produced by people who want you to buy more bottled water." -- pedestrianwolf