Reputation: 5092
I am beginner to Perl , I have trying to read the if...else statement. I tried if..else statement with curly braces.
if ( 1 ) {
print "True\n"; }
else {
print "False\n" ; }
It working properly , then I searched in net how to use single line if statement without using curly braces, they provided same code.
print "True\n" if (1 ) ;
I tried to use the else statement with that sample code
print "false\n" else ;
But I got error message .Can anybody explain how to use the single line else statement with if statement in perl.
Thanks in advance.
Upvotes: 2
Views: 4581
Reputation: 13664
The postfix form of if, like this:
print "blah" if $x==1;
Is referred to as a "statement modifier". The list of all supported statement modifiers can be found in perlsyn. It is:
if EXPR
unless EXPR
while EXPR
until EXPR
for LIST
foreach LIST
when EXPR
Note that else
and elsif
are not amongst them. That means that if you need elsif or else clauses attached to your if, you need to use the longhand form.
Upvotes: 3
Reputation: 15121
I think what you are looking for is unless
:
if condition is true, do something
print "True" if 1;
if condition is false, do something
print "False" unless 1;
Upvotes: 4
Reputation: 35198
Use a Ternary or conditional operator
:
print 1 ? "True\n" : "false\n";
Update
Here's another way to get it all on one line:
if ( 1 ) { print "True\n"; } else { print "False\n" ; }
Upvotes: 5