How do you store a result to a variable and check the result in a conditional?

163 Views Asked by At

I know it's possible but I'm drawing a blank on the syntax. How do you do something similar to the following as a conditional. 5.8, so no switch option:

while ( calculate_result() != 1 ) {
    my $result = calculate_result();
    print "Result is $result\n";
}

And just something similar to:

while ( my $result = calculate_result() != 1 ) {
    print "Result is $result\n";
}
4

There are 4 best solutions below

1
On BEST ANSWER

You need to add parentheses to specify precedence as != has higher priority than =:

while ( (my $result = calculate_result()) != 1 ) {
    print "Result is $result\n";
}
0
On

What's wrong with:

$_ = 1;
sub foo {
   return $_++;
}
while ( ( my $t = foo() ) < 5 )
{
   print $t;
}

results in 1234

2
On

kemp has the right answer about precedence. I'd just add that doing complex expressions involving both assignments and comparisons in a loop condition can make code ugly and unreadable very quickly.

I would write it like this:

while ( my $result = calculate_result() ) { 
    last if $result == 1;
    print "Result is $result\n";
}
0
On

You were close ...

while ( (my $result = calculate_result()) != 1 ) {
    print "Result is $result\n";
}