tags:

views:

78

answers:

2

Possible Duplicate:
Why do you have to put a 1; at the end of a Perl 5 module?

From this page Perl::Critic::Policy::Subroutines::RequireFinalReturn, this is a code sample

package Password;
# every time the user guesses the password wrong, its value
# is rotated by one character
my $password;
sub set_password {
    $password = shift;
}
sub check_password {
    my $guess = shift;
    if ($guess eq $password) {
        unlock_secrets();
    } else {
        $password = (substr $password, 1).(substr $password, 0, 1);
    }
}
1;
  • Why is a 1; used at the end? What does that statement signify to the compiler?

I tried code with and without it. Result looks the same.

+6  A: 

It's because a Perl module has to return "true" in order for it to work as a module. If a module doesn't return true, it's assumed that its initialization failed and it's equivalent to calling die. It's not required if the code isn't used as a module, though, so unless you try using the code example as a module as well, you won't see the difference.

1; is just probably one of the most concise ways of returning true.

If you take a look at this site, you'll see that people are being pretty creative with their return values.

Matti Virkkunen
okay, thats basically anything except `0`, `'0'`, `undef`, `''`, `()`, `('')`.
Lazer
@Lazer : Even `'false'` is true.
Zaid
+4  A: 

Here is a quote from perldoc -f 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.

If I delete the 1; from your module, then try to use it in another script, I get a compile error:

Password.pm did not return a true value
BEGIN failed--compilation aborted
toolic