tags:

views:

86

answers:

4

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";
}
+9  A: 

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
That's it. Forgot = returned the assigned value. Thanks!
Oesor
A: 

What's wrong with:

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

results in 1234

clintp
+2  A: 

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";
}
friedo
This has a different meaning than the OP. The OP will still execute the block if `$result` is false.
mobrule
Yeah, this is really using DateTime's compare(), which is the sub used to override <=> and returns -1, 0, or 1. I need to execute code when it's -1 or 0 and not when 1, and take different paths when -1 and 0.while($result = compare( $time_a, $time_b)) would never execute, basically.
Oesor
A: 

You were close ...

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