6

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";
}
brian d foy
  • 129,424
  • 31
  • 207
  • 592
Oesor
  • 6,632
  • 2
  • 29
  • 56

4 Answers4

9

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

while ( (my $result = calculate_result()) != 1 ) {
    print "Result is $result\n";
}
Matteo Riva
  • 24,728
  • 12
  • 72
  • 104
2

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";
}
Community
  • 1
  • 1
friedo
  • 65,762
  • 16
  • 114
  • 184
  • 2
    This has a different meaning than the OP. The OP will still execute the block if `$result` is false. – mob Apr 22 '10 at 20:51
  • 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 Apr 22 '10 at 21:32
0

What's wrong with:

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

results in 1234

Clinton Pierce
  • 12,859
  • 15
  • 62
  • 90
0

You were close ...

while ( (my $result = calculate_result()) != 1 ) {
    print "Result is $result\n";
}
Brian Roach
  • 76,169
  • 12
  • 136
  • 161