Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl does not complain about missing semicolon

Tags:

semantics

perl

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?

like image 616
slayedbylucifer Avatar asked May 09 '13 09:05

slayedbylucifer


People also ask

Is semicolon mandatory in Perl?

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.

Can a JavaScript statement still run without semicolon?

JavaScript interpreters will add semicolons for you. Omitting semicolons is a very bad idea as it can cause interpreted JavaScript code to behave differently than you'd expect due to this. See the breaking examples on Wikipedia: return a + b; // Returns undefined.

Where is the semi colon on Iphone 12?

If you're using the built-in iOS keyboard, tap the "123" key in the lower left-hand corner of the keyboard. The colon and semi-colon are located to the left of the parenthesis.

Does C# need semicolon?

Semi-colons will always be required, it will not change. So the answers that talk about how C# would work without them are moot.


2 Answers

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.

like image 83
Quentin Avatar answered Sep 23 '22 20:09

Quentin


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).

like image 22
Matthew Walton Avatar answered Sep 20 '22 20:09

Matthew Walton