Perl require and variables

Hello,

I’ve read this: http://perldoc.perl.org/functions/require.html

and in my example I try to “include” a perl file to another but I get errors:

Global symbol “$var1” requires explicit package name at ./1.pl line 8.
Global symbol “$var2” requires explicit package name at ./1.pl line 9.
Execution of ./1.pl aborted due to compilation errors.

Code of the two files:

1.pl


#!/usr/bin/perl -w
use strict;
require '2.pl';
print $var1;
print $var2;

2.pl


#!/usr/bin/perl -w
my $var1 = "hello";
my $var2 = " perl!";

I’ve also tried these, but every time, I get the same errors:
2.pl


#!/usr/bin/perl -w
local $var1 = "hello";
local $var2 = " perl!";

2.pl


#!/usr/bin/perl -w
our $var1 = "hello";
our $var2 = " perl!";

and

1.pl


#!/usr/bin/perl -w
use strict;
package HelloWorld
require '2.pl';
print $var1;
print $var2;

2.pl


#!/usr/bin/perl -w
package HelloWorld
my $var1 = "hello";
my $var2 = " perl!";
1;

Could somebody explain me these? Is it cause they aren’t in the same scope?
I’ve coded PHP for couple years, and now learning Perl.

Thanks :slight_smile:

Correct, the variables in the required file are not scoped for the main file. There is little sense in just posting the code for how to do what you want since you will not understand what the code is doing. Read Chapter 10, “Modules”, of this free online perl book:

and you will probably want to bookmark that site for future reference.

Thanks for your reply,

The solution I came with was:

1.pl


#!/usr/bin/perl -w

use strict;
use TestModule;

print "\
\
";

print $TestModule::var1;
print $TestModule::var2;

print "\
\
";

TestModule.pm


package TestModule;

use strict;
our $var1 = "hello";
our $var2 = " perl!";

1;

That is one way to do it but is not the typical way. Read the link I posted for you. But congratulations on finding a solution that is perfectly acceptabe for your small example. You wouldn’t want to use that convention for more complex programs though.

I too am having this issue and nothing seem to work. Here’s an example of some code that fails:

file.inc

my %data = (‘one’=> 1, ‘two’ => 2, ‘three’ => 3);
1;

test.pl

#!/usr/bin/perl

use strict;

require “file.inc”;

#my %data = (‘one’ => 1, ‘two’ => 2, ‘three’ => 3);

foreach my $key (sort keys %data) {
print "$key = $data{$key}
";
}

exit;

If I uncomment the local variable definition, of course it works, and if I take out “use strict” and don’t include the “my” for %data in the include file it also works. Using perl 5.8.8 on Linux

try:

file.inc

our %data = (‘one’=> 1, ‘two’ => 2, ‘three’ => 3);
1;