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

I am used to declaring my common variables in a single PHP file, and then doing an include_once in any PHP script using those variables. What would be the equivalent in perl, while avoiding having the same variables load multiple times?

Replies are listed 'Best First'.
Re: Variables in a single file
by almut (Canon) on Sep 16, 2009 at 12:35 UTC

    If you use use or require, Perl makes sure that the module (or simply a codeblock of variable declarations) is loaded only once.  Note, however, that the loaded file has its own implicit lexical scope — which matters for variables declared with my or our ...

      Unfortunately accessing an undeclared variable which was required from another file can lead to "undefined variable"-warnings.

      Importing with use might be more complicated but it works with warnings enabled.

      @OP: You may wanna have a look at Exporter

      Cheers Rolf

      UPDATE: added "undeclared"

        ...can lead to "undefined variable"-warnings

        Could you provide an example?  I think you're fine as long as you make sure the code has loaded/compiled before you access the variables (using use or require within a BEGIN block):

        ---- X.pm ---- $::foo = "foo"; $::bar = "bar"; -------------- #!/usr/bin/perl use strict; use warnings; use X; # or BEGIN { require X; } print "$::foo\n"; # no warnings
Re: Variables in a single file
by Corion (Patriarch) on Sep 16, 2009 at 12:34 UTC

    do resp. require, both setting global variables. do will (re)load the file, while require seems to be closer in what it does to the name of include_once (which I don't know what it does).

Re: Variables in a single file
by leocharre (Priest) on Sep 16, 2009 at 16:00 UTC
    Well, what is your code? Is it a script only? Then here's one example..
    #!/usr/bin/perl use strict; use vars qw/$NAME $AGE $DATE/; $NAME = 'jim'; $AGE = 29; $DATE = `date`;

    In that example, the variables reside in namespace main::, so that from anywhere in the program, $main::AGE will hit 29 in this example.

    If this were a module..

    package Sunflower; use strict; use vars qw/$NAME $AGE $DATE/; $NAME = 'jim'; $AGE = 29; $DATE = `date`;

    Then from anywhere in the code (there are some variations), you can access $Sunflower::AGE.

    (You do have to realize that if you code a module (pm), then that example there, those values are set at compile time, before your code calling 'use Sunflower;' runs.. Worry about this later.)

    I would say if you expect your values to change from time to time.. How about a YAML config file?

    #!/usr/bin/perl use strict; use YAML; my $abs_conf = '/etc/sunflower.conf'; my $config_data = YAML::LoadFile($abs_conf); printf "Age is %s, name is %s, date is %s\n", $config_data->{AGE}, $config_data->{NAME}, `date`;

    And in your /etc/sunflower.conf..

    ---
    AGE: 29
    NAME: jim