What happens if you don't put 1;
at the end of a package? For example, if I remove the 1;
from the following script, the code still runs:
#!/usr/bin/perl
package Foo;
print "Begin and Block Demo\n";
BEGIN {
print "This is BEGIN Block\n"
}
END {
print "This is END Block\n"
}
1;
Is the 1;
mandatory for package creation? I saw this question, but it doesn't explain what happens if the 1;
is omitted.
This is a little tricky. It is simply required, if the package will be loaded by use
or require
.
From require
The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with
1;
unless you're sure it'll return true otherwise. But it's better just to put the1;
, in case you add more statements.
The use comes down to require
, so whenever you use
a module the last statement that returns must return true, otherwise the compilation fails. A simple way to ensure this is to put 1;
at the end. If you never use
(or require
) that package then you don't have to have the 1
(true) in it.
The code in a file brought into the program via use
actually runs and it must end up returning true, as required by require
. If the file is read in in another way then there is no notion of 'return'.
If it is run as an executable then again there is no requirement on true return, since require
isn't involved. However, we generally write packages in order to use
them, not to run them as programs. So practically speaking there should always be a 1;
at the end.
The perlmod would also be required reading.
Here is a simple example. This
File Mod.pm
package Mod;
# print "hello\n"; # works with this line uncommented
File script.pl
use Mod;
when run by perl script.pl
prints
Mod.pm did not return a true value at main.pl line 1. BEGIN failed--compilation aborted at main.pl line 1.
When a package is use
d it must return a true value. If the last return is from a statement which happens to return true, like the commented out print
, then all is well again.
But we can run perl Mod.pm
regardless of what it returns.
When you use
a .pm
file, the file must return a true value (such as 1
) to indicate success, or else the use
statement will fail and compilation will be aborted.
But packages, as such, don't have to end with a true value; it's just that usually each package goes in its own .pm
file, and the file needs the 1
in order to be use
-able. In your example, where the package is put directly inside an executable script, no 1
is needed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With