Perl lets you omit semicolons at the end of a block. That is, you can treat ;
as a statement separator, not a terminator, as in Pascal.
OK, but why would you want to do that? The advantage of terminating each
statement is that you don't need to do anything special for the first and last
lines: You can insert or remove lines at any point without worrying about the
rest of the code. Why throw that away?
Because sometimes it doesn't make sense to add code at the end. Consider this
code:
sub foo {
my ($s) = @_;
$s =~ s/%/%%/g;
$s
}
The last statement $s
is the return value. Adding statements after it could
silently break this function. By omitting the last semicolon I can make the
code a bit more robust, because now I get a syntax error when I try to put more
code at the end without paying attention.
Maybe you don't use this form of code, though. Maybe you always write an
explicit return
. In that case any following code is silently ignored, so in
the above scenario you wouldn't break anything, but your changes wouldn't have
any effect either.
And there's another case that affects everyone who writes modules. Files loaded
by require
(directly or indirectly via use
) need to return a true value.
Most people simply write 1;
at the end of their modules. I think it makes
sense to omit the ;
here as well, because nothing should come after it.
I've actually seen people cargo-cult module code, putting 1;
in the middle of
their Perl files. For those people: 1;
doesn't make sense unless it's the
last statement in a file and that file is a module. Everyone: you should end
your modules with 1
, not 1;
.
(That's what I think, anyway. I hope this posting makes some sense.)