[comp.lang.perl] loops, conditional expressions, and pattern match variables

jbw@bucsf.bu.edu (Joe Wells) (03/08/90)

Discovered an interesting undocumented gotcha with the use of $1 and
related pattern match variables, illustrated by the following short
program:

    $_ = 'foobar';
    m/^(...)(...)$/;
    print "A 1: $1, 2: $2\n";
    while (! m/^(..)(..)$/)
      {
	print "B 1: $1, 2: $2\n";
	$_ = 'fubu';
      }
    print "C 1: $1, 2: $2\n";

    while (! m/^(..)(..)$/)
      { print "never reached\n"; }
    print "D 1: $1, 2: $2\n";

which produces this output:

    A 1: foo, 2: bar
    B 1: foo, 2: bar
    C 1: foo, 2: bar
    D 1: fu, 2: bu

Essentially, the first time the EXPR in a "while" statement is evaluated,
any changes to the values of the pattern match variables ($1, $&, et. al.)
are visible outside the while statement.  The second and succeeding times
the EXPR is evaluated, such changes are only visible inside the loop.

Neat, huh?  Sure threw me for a loop.

-- 
Joe Wells <jbw@bu.edu>
jbw%bucsf.bu.edu@cs.bu.edu
...!harvard!bu-cs!bucsf!jbw