Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you don't put 1; at the end of a package?

Tags:

perl

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.

like image 586
sureshkumar Avatar asked Jan 04 '23 15:01

sureshkumar


2 Answers

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 the 1;, 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 used 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.

like image 79
zdim Avatar answered Jan 14 '23 12:01

zdim


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.

like image 26
ruakh Avatar answered Jan 14 '23 12:01

ruakh