How do you store a result to a variable and check the result in a conditional?
Question
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";
}
Solution
You need to add parentheses to specify precedence as !=
has higher priority than =
:
while ( (my $result = calculate_result()) != 1 ) {
print "Result is $result\n";
}
OTHER TIPS
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";
}
What's wrong with:
$_ = 1;
sub foo {
return $_++;
}
while ( ( my $t = foo() ) < 5 )
{
print $t;
}
results in 1234
You were close ...
while ( (my $result = calculate_result()) != 1 ) {
print "Result is $result\n";
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow