开发者

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

开发者 https://www.devze.com 2022-12-27 16:32 出处:网络
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:

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";
}


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

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


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";
}
0

精彩评论

暂无评论...
验证码 换一张
取 消