Evan Carroll
Evan Carroll

Reputation: 1

In what ways does explicit package main perform differently than an implicit package main?

I was under the impression that a file that starts

use constant FOO => rand();

was effectively

package main;
use constant FOO => rand();

However, if I have two files with the constant declaration above, and one file requires the other file everything will work, while the second one will generate a warning.

Constant subroutine main::FOO redefined at /usr/lib/x86_64-linux-gnu/perl-base/constant.pm line 171.

For reference, here is the code I'm using in f1.pl, and f2.pl is the same but with the require removed.

# in `f1.pl`
package main;
no warnings;
use constant FOO => rand();

package Other;
require "f2.pl"; # this line should be removed from f2.pl

1;

In what ways does an implicit package main work differently from an explicitly package main?

Upvotes: 4

Views: 250

Answers (1)

Grinnz
Grinnz

Reputation: 9231

The package statement is less a declaration and more an action on that lexical scope. A file with package main; will switch to that package, regardless of what the current package is when it is required; without it, it will execute in the context of the package that was active when it was required.

Upvotes: 4

Related Questions