develooper Front page | perl.beginners | Postings from July 2003

RE: Is $1 ever undefined or set to null?

Thread Previous | Thread Next
From:
Jeff 'japhy' Pinyan
Date:
July 21, 2003 13:40
Subject:
RE: Is $1 ever undefined or set to null?
Message ID:
Pine.LNX.4.44.0307211627340.10732-100000@perlmonk.org
On Jul 21, Jeff 'japhy' Pinyan said:

>This is the issue.  Why are the $DIGIT variables bound to the block
>they're in IN TOTALITY, rather than for the life of the execution of the
>block?

It's actually slightly more complex than that.

Here's a piece of code like what Steve wrote:

  sub match {
    ($1 + 1) =~ /(\d+)/;
    print $1;
    match() if $1 < 2;
    print $1;
  }

  "0" =~ /(\d+)/;
  match();

Now, this code prints "1222".  Odd.  Baffling, even.  Why doesn't it print
"1221"?  Because the $DIGIT variables are not just magically scoped,
they're magic themselves.  They are connected to the last successful
pattern match, yes, but more importantly, they are DIRECTLY connected to
the last PMOP (an internal structure representing the pattern match).

Even though calling the function creates a new block, the underlying PMOP
is the SAME ONE.  Watch what happens when we do this:

  sub match {
    $R++ ? ($1 + 1) =~ /(\d+)/ : ($1 + 1) =~ /(\d+)/;
    print $1;
    match() if $1 < 2;
    print $1;
  }

  "0" =~ /(\d+)/;
  $R = 0;
  match();

It prints "1221".  Why?  Because the second time match() is called, a
DIFFERENT PMOP is used.  It might be confusing, but it's the way things
go.

-- 
Jeff "japhy" Pinyan      japhy@pobox.com      http://www.pobox.com/~japhy/
RPI Acacia brother #734   http://www.perlmonks.org/   http://www.cpan.org/
<stu> what does y/// stand for?  <tenderpuss> why, yansliterate of course.
[  I'm looking for programming work.  If you like my work, let me know.  ]


Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About