Perl Require

extern: index | reference
intern: preamble | sample | end

Preamble

For a long time I have regularly using Perl's 'require' to include a set of library type functions. This works very well, and now just about every perl script I write begins with :-

use strict;
use warnings;
require 'logfile.pl' or die "Unable to load logfile.pl!\n";

So much so, that it is included in my 'template' to create every new perl file.

But up until recently I have never tried to put 'variables' in these 'include' library files. The problem was how to access these 'external' variables! Since Perl 5.6, the great 'our' comes to the rescue ;=))

Of course, if you read the PERLDOC information on this 'require', you will only find a very brief mention that is can be used to 'include' external 'library' like files, and no mention of how to access the 'variables' ;=() But then the use of 'our' is quite 'new', and maybe has not yet percolated through the massive amount of perl documentation...


top

Sample

The 'variable' include (require) file called 'test_req2.pl' ... in this case defining values for '$testv1', and '$testv2'...

code:

# test_req2.pl - test values
use strict;
our $testv1 = <<EOF;
string 1
EOF
our $testv2 = <<EOF;
string 2
EOF
1; # so the 'require' succeeds

And then a file, test_req1.pl, to use these two(2), sort of 'external' variables ...

# test_req1.pl - 25 August 2009 - testing 'require', for variables
use strict;
use warnings;
require 'test_req2.pl' or die "Unable to load test_req2.pl!\n";
our($testv1, $testv2);
my $test = $testv1;
print $test;
$test = $testv2;
print $test;

output:

string 1
string 2

For a little more on 'our'. That is it, for now ...


top

EOF - perl_require.htm

checked by tidy  Valid HTML 4.01 Transitional