$df{key} =10 ; return ; if $result == 10 ;
gives me an error. How can I achieve this?
$df{key} =10 ; return ; if $result == 10 ;
gives me an error. How can I achieve this?
The post-statement form of if
only works with single statements. You will have to enclose multiple statements in a block after the if
condition, which itself needs to be enclosed in parentheses:
if ( $result == 10 ) {
$df{key} = 10;
return;
}
In this case, it is possible to combine the two statements with a post-statement conditional. The idea here is to combine the two statements in one by performing a Boolean evaluation.
However, this is not a good idea in general as it may short-circuit and fail to do what you expect, like when $df{key} = 0
:
$df{key} = 10 and return if $result == 10;
From perlsyn:
In Perl, a sequence of statements that defines a scope is called a block
... generally, a block is delimited by curly brackets, also known as braces. We will call this syntactic construct a BLOCK.
The following compound statements may be used to control flow:
if (EXPR) BLOCK
if (EXPR) BLOCK else BLOCK
if (EXPR) BLOCK elsif (EXPR) BLOCK ... else BLOCK
You can group the statements into a do BLOCK
and use a conditional
statement modifier on that compound statement.
do { $df{key} = 10; return } if $result == 10;
Unlike the and
construct posted by Zaid, this is not ambiguous. You
should, however, think twice before using a conditional statement
modifier. Especially mixing if
/unless
statements with
if
/unless
statement modifiers reduces readability of your code.
The main case where in my opinion the statement modifiers make sense are uncomplicated error paths, i.e.:
croak "foo not specified" unless exists $args{foo};
The comma operator allows one to chain together multiple statements into an expression, after which you can include the conditional:
$df{key} = 10, return if $result == 10;
I use this construct quite often when checking for error conditions:
for my $foo (something...)
{
warn("invalid thing"), next unless $foo =~ /pattern/;
# ...
}