27

I just found on my Ubuntu that Perl is not complaining about the semicolon at the end. Check the following code:

#!/usr/bin/perl
use warnings;
use strict;

my @array = (1, 2, 3, 4);

foreach (@array)
{
    print $_."\n"
}

print "no, this cant be true"

Please notice that semicolon ";" is missing from the print statement. Still the code runs fine.

OUTPUT:

1
2
3
4
no, this cant be true

If I put semicolon after print, it still works. So this is confusing to me.

Could you help me understand what am I missing here, OR is there some obvious Perl ideology that I overlooked?

Peter O.
  • 32,158
  • 14
  • 82
  • 96
slayedbylucifer
  • 22,878
  • 16
  • 94
  • 123
  • It doesn't complain about "extra" semi-colons either. Same goes for "extra" and "missing" commas. – ikegami May 09 '13 at 09:31
  • 2
    From the archives: [a program that only runs when you forget the semi-colon](http://stackoverflow.com/q/11695110/168657) – mob May 09 '13 at 14:51
  • This is actually very handy in one-line eval blocks. Consider saying "eval {$some->method};" verses saying "eval {$some->method;};". – David Mertens Oct 17 '13 at 13:37

3 Answers3

54

From perldoc perlsyn:

Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional.

Your print statement is the last statement in a block.

Omitting the semi-colon isn't recommended though. It's too easy to forget to add it if you extend the block later.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
12

I often think of semicolons in Perl as separators rather than terminators - that makes this behaviour a lot easier to get used to.

That said, it's not at all a bad idea to always use a semicolon as you don't have to remember to add it later if you put more statements at the end of the block, a bit like using an extra comma in a list so that you don't forget to add that later (Perl ignores the last comma if there's no list item after it).

Matthew Walton
  • 9,809
  • 3
  • 27
  • 36
9

From the Perl documentation:

Every simple statement must be terminated with a semicolon, unless it is the final statement in a block, in which case the semicolon is optional.

Andomar
  • 232,371
  • 49
  • 380
  • 404