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

Hie monks, I have got a problem with the require function and default package.I cannot understand the following behavior.

I have a script
use strict; use warnings; require "env.pl"; foreach my $file("env.pl","env1.pl") { $main::var="default"; require "${file}"; print "\nIn $file var is : $main::var\n"; }
and a file 'env.pl' which contains
$var="env"; 1;
Another file 'env1.pl' which contains
$var="env1"; 1;
All in the same folder.Now If I run the script I get the o/p
In env var is : default In env1 var is : env1
But If I comment Line 4
require "env.pl"
in my script It works fine. So Why is that If read $main::var then modify it then read it again from the same file it's value is not changing??
I suspect that the 'require' in the for loop sends the variable to some other package other than main.

The world is so big for any individual to conquer

Replies are listed 'Best First'.
Re: Problem with require and default package
by Corion (Patriarch) on Dec 21, 2007 at 10:04 UTC

    require only loads a file once. If you want to load a file multiple time, have a look at do.

      So does it imply that 'require' just Pulls in the contents whereas 'do' executes them??

      The world is so big for any individual to conquer

        No, they both execute the code. perlfunc discusses the difference and generally encourages require over do. Another possibility is to remove the file's entry from %INC so that perl loads the file again, for example:
        require 'gash2.pl'; $var = 37; # do some stuff delete $INC{'gash2.pl'}; require 'gash2.pl';