tags:

views:

86

answers:

3
$df{key} =10 ; return ; if $result == 10 ;

gives me an error. How can I achieve this?

+7  A: 

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

Zaid
+3  A: 

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};
hillu
I know that `do { } while` is guaranteed to execute at least once. Does this mean that `do { } if` will do the same thing?
Zaid
I just tried it. `do { print "hello\n" } if 0;` will print nothing, as expected.
hillu
+3  A: 

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/;
    # ...
}
Ether
Don't forget the parentheses around the warning, or `warn` will gobble up `next`!
Zaid
@Zaid: good point! In my own code, `warn` is actually `$this->warn(...)` so the parentheses are already there... or I would have been bitten by this :)
Ether