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

Dear Monks,

I have created a library called util.pm which contains a bunch of subroutines. A few perl scripts make use of this library by doing

BEGIN { my $dir = dirname($0); require "$dir/../util.pm"; }
I wish to have a few variables in util.pm that can also be visible in the perl scripts. However, perl will not let me do this - perl scripts having the above block are only able to aceess the subroutines in util.pm and not the variables.

One option is have the standard @EXPORT_OK stuff and have my scripts do "use util.pm".

Is there any other method to achieve what I want?

Thanks!

Replies are listed 'Best First'.
Re: Using variables declared in a library from other perl scripts
by GrandFather (Saint) on Apr 19, 2007 at 00:00 UTC

    Given a module file nonam1.pm containing:

    use strict; use warnings; package noname1; our $wibble = 'Hello World'; 1;

    then a Perl source file in the same location containing:

    use strict; use warnings; BEGIN { require "./noname1.pm"; } print $noname1::wibble;

    prints:

    Hello World

    as does:

    use strict; use warnings; use noname1; print $noname1::wibble;

    Update: Remove broken and needless cruft from module code (see anno's reply).


    DWIM is Perl's answer to Gödel
      use EXPORTER; package noname1; our @EXPORT_OK = qw($wibble); our $wibble = 'Hello World'; 1;
      You must be on a case-insensititve file system. It should be "use Exporter;". But "Exporter" does nothing in your code. It would work exactly the same without "use Exporter;" and without setting "@EXPORT_OK".

      What happened? Your replies are usually more to the point.

      Anno

        Late afternoon brain fade and rush due to demands of $work are the only excuse I can give. :(

        Node updated.


        DWIM is Perl's answer to Gödel
      Thanks very much - the above code works very well for my needs.

      Cheers

Re: Using variables declared in a library from other perl scripts
by chromatic (Archbishop) on Apr 18, 2007 at 23:53 UTC
    Is there any other method to achieve what I want?

    Yes, but the use option is likely the simplest and clearest. Another option is to refer to the variables with their fully-qualified forms.