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?
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.
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.
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.
Semi-colons will always be required, it will not change. So the answers that talk about how C# would work without them are moot.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With