For as long as i have been using Perl I have been aware of three ways to use if.
if(condition){
"do this";
"do that";
}
"do this" if condition;
condition ? "do this" : "or this";
However I thought the last two could only be used if you only had a single command to be performed. However recently I learned that when using the second option you can do more than one command by separating them with a comma.
perl -e '$count++, $var="Hello" if 4 < 5; print "COUNT: $count, VAR: $var\n"'
COUNT: 1, VAR: Hello
I realise the use cases are limited for this but it sparked my interest. I was trying to look through the perldoc to find the syntax that documents this behavior but couldn't see anything explaining that multiple commands can be used if separated by comma.
Is this behavior specific to using the if statement in this way, or does it work due to some other feature of Perl? if someone can point me to any documentation on the behavior that would be great.
Is this behavior specific to using the if statement in this way, or does it work due to some other feature of Perl?
No, this is not specific to the post-fix if. In fact, every statement can be a list of several things. Sometimes that makes sense, and sometimes it doesn't.
print 1, 2;
print(1, 2);
print( (1, 2) );
print( ( (1), (2) ) );
These are all equal, because lists will be flattened in Perl. The same way, you can have function calls there.
foo(), bar();
( foo(), bar() );
The associativity will not always be as clear as here, so it makes sense to use parenthesis in certain cases.
However, if you want a post-fix if and a block, you should use a block. You answered your own question in the title, really. Use the do language construct.
do {
foo();
bar();
} if $condition;
Of course, if you do that, you can just as well use a proper if block.
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