Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the 1 at the end of each perl package?

If you forget the 1 at the end of a package, Perl tells you "The package didn't return a true value". Well, if it knows you forgot it, why not just put it there for you?

like image 937
miniml Avatar asked Mar 13 '11 23:03

miniml


People also ask

What does 1 mean in Perl?

1 at the end of a module means that the module returns true to use/require statements. It can be used to tell if module initialization is successful. Otherwise, use/require will fail. $somevar is a variable which is accessable only inside the block. It is used to simulate "static" variables.

In which block you can modify $? To change the exit value of the program?

Inside an END code block, $? contains the value that the program is going to pass to exit() . You can modify $? to change the exit value of the program.

What is package name in Perl?

A Perl package is a collection of code which resides in its own namespace. Perl module is a package defined in a file having the same name as that of the package and having extension . pm. Two different modules may contain a variable or a function of the same name.


2 Answers

Because Perl modules are required to return a value to signal if the require directive must succeed (true value returned) or fail (false value returned; this can make sense if the module failed to initialize for some reason).

If you don't return anything, the interpreter cannot know if the require must succeed or fail; at the same time, since it's easy to forget to put the true value at the end of the package, it suggests the "common fix" for this error: add a true value as a return.

For some other info/folklore about the modules return value have a look at this question.

like image 157
Matteo Italia Avatar answered Sep 30 '22 18:09

Matteo Italia


A package can return a false value if it fails to initialize, for example if it couldn't find a required data file or external library. This way it fails cleanly at load time (and this failure can even be tested for) rather than unpredictably later.

like image 28
Anomie Avatar answered Sep 30 '22 17:09

Anomie