in reply to Variables in a single file

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 ...

Replies are listed 'Best First'.
Re^2: Variables in a single file
by LanX (Saint) on Sep 16, 2009 at 13:41 UTC
    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
        sorry, my memory was wrong one gets a

        Name "main::x" used only once: possible typo at ... warning.

        But putting the require into a begin block really helps. 8)

        > cat mod.pm tren prog.pl tren; perl prog.pl $x="X"; 1; ------------------------ use strict; use warnings; #our $x; #BEGIN { require mod; #} print $::x; ------------------------ Name "main::x" used only once: possible typo at prog.pl line 10. X

        Cheers Rolf