Perl does not complain about missing semicolon

早过忘川 提交于 2020-01-13 07:32:32

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!