问题
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?
回答1:
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.
回答2:
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).
回答3:
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.
来源:https://stackoverflow.com/questions/16458193/perl-does-not-complain-about-missing-semicolon