How to save the result in a variable and check the result in a conditional expression?

I know this is possible, but I draw a space in the syntax. How do you do something similar to the following as conditional. 5.8, so there is 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"; } 
+6
perl
source share
4 answers

You need to add parentheses to indicate priority, because != Has a higher priority than = :

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

kemp has the correct priority answer. I would add that executing complex expressions, including both assignments and comparisons in a loop, can make the code ugly and unreadable very quickly.

I would write this as follows:

 while ( my $result = calculate_result() ) { last if $result == 1; print "Result is $result\n"; } 
+2
source share

What happened with:

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

leads to 1234

0
source share

You were close ...

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

All Articles