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

This question is a follow on question to a previous one at http://www.perlmonks.org/?node_id=1057587, from a number of days back. I did post this follow-up query in that post, but I think the post is probably not being viewed any more.

So, the original question was to do with passing arguments from a script to a module; I can now get that bit working. However, the solution seems to introduce another problem, which I don't quite understand.

The test module, and test script, are shown below:

The module
package my_testmodule; $VERSION = '1.00'; use strict; use warnings; our $gMessage; undef our @list; use Exporter; our @ISA = qw(Exporter); our @EXPORT = qw(@list); sub import { my $class = shift; $gMessage = shift; print "Yep, I'm in here ...\n\n"; my_sub(); } # &my_sub; sub my_sub { print "$gMessage\n\n" if ($gMessage); push (@list,'oranges','lemons','apples'); } 1;
The script
#!/usr/bin/perl use strict; use warnings; use my_testmodule 'xyz'; print "$list[0]\n\n"; exit;

Previously, before trying to pass the module anything at all, and thus without the import sub, I would be able to read @list, defined in the module, in test.pl.

However, now, with the import sub, I'll get an error when running test.pl, "Global symbol "@list" requires explicit package name at test.pl line 8."

I don't see why this should be, seeing as it appears to be defined and exported properly in the module; in fact nothing to do with @list has changed.

I did also try referencing $list with the package name, but that doesn't work either.

Any help/suggestions would be much appreciated. Thanks!

Replies are listed 'Best First'.
Re: Variable Scope
by jdporter (Paladin) on Oct 10, 2013 at 00:39 UTC

    The problem -- and it is admittedly a subtle one -- is that if your module isa Exporter, then the semantics of argument passing to the module is (re)defined by Exporter. As the docs clearly state, arguments you pass to the use of an Exporter-derived module are supposed to be the symbols you want to import from it.

    Of course, you're not seeing the error that should occur because you're also re-defining import, rather than using the one provided by Exporter. The docs, at section "Exporting without using Exporter's import method", explain how to do what you're trying to do. In a nutshell, add the following line to your import sub:

    $class->export_to_level(1,);
    I reckon we are the only monastery ever to have a dungeon stuffed with 16,000 zombies.

      Ah, thank you so much. Yes, I've now tried that and it works as expected.

      Many thanks!!