I have a question about how perl executes the "do" function.
suppose I have a function that goes something like this:
sub foo {
package bar;
%bar::h_test = ('b' => 'blah');
}
when using strict and warnings, this will run just fine. now suppose I have the following perl script, "test.pl":
%h_test = ('b' => 'blah');
now I can rewrite the previous function as follows:
sub foo {
package bar;
do ('test.pl');
}
it seems that "do" lets me use unqualified names, as long as I keep them in a file. I understand why this makes sense from a design stand-point, since every script out there can't possibly be aware of whoever is calling it. However, I'm not sure what are the precise rules of running code with "do" that allow it.
So, how does it work? Reading the perldoc didn't shed much light on the subject
Thanks.
The reason you do not get a compile time error when you do not declare %h_test
with our
in test.pl
, is that the use strict
that you have in your main script do not extend to the file test.pl
. According to the documentation:
The
strict
pragma disables certain Perl expressions that could behave unexpectedly or are difficult to debug, turning them into errors. The effect of this pragma is limited to the current file or scope block.
Also note that the documentation for do
says:
do './stat.pl'
is largely like:eval `cat stat.pl`;
except that it's more concise, runs no external processes, and keeps track of the current filename for error messages. It also differs in that code evaluated with do FILE cannot see lexicals in the enclosing scope
Also, according to the documentation use strict 'vars'
does not generate an error if a name is fully qualified. So that explains why you can write %bar::h_test = ('b' => 'blah')
when using strict
and whithout declaring the variable with our
.