[Tucson-pm] while and until statements

Jasvir Nagra jas at cs.arizona.edu
Thu Dec 9 21:13:18 CST 2004


You have a minor bug in CODE_2 which is responsible for the difference.
It ought to read:

$x = 1;
until ($x == 4)               # == tests equality, = is assignment
{
    print "$x\n";
    $x++;
}

If you use assignment, the $x is assigned 4 immediately which is
interpreted as true so print never executes.

-- Jasvir

On Thu, 2004-12-09 at 23:35 -0700, Day Irmiter wrote:
> In the third edition of "Programming Perl" (the "camel book", 2000), page 115 reads as follows.
> 
> "The 'while' statement repeatedly executes the block as long as EXPR is true. If the word 'while' is replaced by the word 'until', the sense of the test is reversed; that is, it executes the block only as long as EXPR remains false." Makes sense to me, except in practice the effect of the two statements is not parallel.
> 
> ---
> CODE_1:
> $x = 1;
> while ($x != 4)
> {
>     print "$x\n";
>     $x++;
> }
> ---
> OUTPUT_1:
> H:\Perl>perl -w temp
> 1
> 2
> 3
> 
> ---
> CODE_2:
> $x = 1;
> until ($x = 4)
> {
>     print "$x\n";
>     $x++;
> }
> ---
> OUTPUT_2:
> H:\Perl>perl -w temp
> 
> H:\Perl>
> 
> In other words, with the until statement, the print statement does not execute. And yet, if the second bit of code is run under the debugger, it will be seen that $x is incremented to 4. Anybody have any comments about this? I'm running the ActiveState 5.8.4 binary under Win98, by the way. I'd be interested to know if running the above code on a Unix platform yields the same result.
> 

-- 
Jasvir Nagra
http://www.cs.auckland.ac.nz/~jas




More information about the Tucson-pm mailing list