Reputation: 365
So I have 3 perl files ( 1.pl, 2.pl, 3.pl) , I want to require a value from a loop in 2.pl and print it in 3.pl
the scripts
1.pl
use strict;
use warnings;
require "./2.pl";
sub red {
our $var;
print "try : ";
require "./3.pl"
}
2.pl
use strict;
use warnings;
my @array = ("http://exemple.org", "http://test.org","http://perl.org");
foreach our $var(@array){
chomp ($var);
red();
}
1;
3.pl
use strict;
use warnings;
our $var;
print "3 : $var\n";
1;
What I get when I open 1.pl in terminal :
try : 3 : http://exemple.org
try : try :
And what I want to get is :
try : 3 : http://exemple.org
try : 3 : http://test.org
try : 3 : http://perl.org
It seems like the 2nd require of 3.pl dont work , so what can I do?
Upvotes: 0
Views: 46
Reputation: 54371
The require
keyword stores files it has already loaded in the %INC
hash.
perl -MData::Dumper -E 'say Dumper \%INC'
$VAR1 = {
'Data/Dumper.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/x86_64-linux/Data/Dumper.pm',
'constant.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/constant.pm',
'feature.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/feature.pm',
'strict.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/strict.pm',
'warnings/register.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/warnings/register.pm',
'Exporter.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/Exporter.pm',
'XSLoader.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/XSLoader.pm',
'bytes.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/bytes.pm',
'warnings.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/warnings.pm',
'Carp.pm' => '/home/simbabque/perl5/perlbrew/perls/perl-5.26.1/lib/5.26.1/Carp.pm'
};
When you try to require $same_filename
again, it will look at $INC{$same_filename}
. If that exists, it aborts.
If you want to re-run the same file you can use the do
keyword instead, which just loads and executes a file. This will re-read the file from disk every time.
sub red {
our $var;
print "try : ";
do "./3.pl"
}
Keep in mind that this is really bad practice. You should move this code into a function and pass lexical variables around.
Upvotes: 5