The last statement

Days ago, I was learning to use CGI::Application.

After finished my baby "run mode", I opened my browser to give it a shot. It worked, and I start wondering why it worked. The last statements of those examples are

return $output;

Mine's not, it looked like this(I forgot to add "return" by accident):

sub run_mode_1 {
    my $self   = shift;
    my $query  = $self->query();
    my $output = q[];
    ... ... 
    $output .= $query->end_html;
}

Suddenly I realized it's the last statement! Its value had become the return value of the subroutine(As far as I know, it must return something, either through a "return" or the last expression evaluated). There's no black magic for that, everything went on well enough.

For a code block, the trailing semicolon of the last statement can be omitted. It's an eye-candy for using in some scenario such as map/grep.

For a module, the last statement must be a true value, the commonly-used one is "1;" or you'll get lines like this:

Homework.pm: Your/Homework.pm did not return a true value at homework.pl line 4.
BEGIN failed--compilation aborted at homework.pl line 4.


__END__

It("__END__" or "__DATA__") is yet-another-last-statement. As Larry told us in this article, we put this at the ending of our scripts as if we just told people "and they lived happily ever after". Everything comes after will not be treat as Perl code, and can access via a special file handle called "DATA".

1 Comment

The last thing evaluated in a subroutine is the default "return". I believe that is the rule.

It is a good habit to put that "return" in there as it is easier to see what is going on and what you really meant to happen. More so for people coming after you.

Leave a comment

About pid

user-pic I blog about Perl.