[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] $1 issues



At 12:41 96-02-09, yeah wrote:

>This is my situation: I'm using parentheses within a pattern-match
>construction in a subroutine, and setting variables to the contents of
>$1, _conditionally_, based on whether the match succeeded. However, testing
>indicates that when the match FAILS, the previous value of $1 is used anyway!

Of course! See page 111 in Programming Perl:
        ...All of them are associated with the last successful pattern
        match. ... Contains the subpattern from the corresponding set of
        parentheses in the last pattern matched, not counting
        patterns matched in nested blocks that have been exited
        already.

>The way I interpret the docs, this is incorrect: $1 .. $9 are automatically
>local to the block -- which to me means that when the subroutine exits,
>these values are set to null or 0 or whatever. Possibly my understanding
>is incorrect...

Where does it say anywhere that the values are set to null?  The
variables are simply are not available in the outer context.  When you
re-enter that context, and don't explicitly reset them, why shouldn't
they still have the older values?  (Although I wouldn't write code that
dependended upon this behavior.)

The "spec" for perl is silent on what the meaning upon re-entry would
be.  The only thing that is guaranteed is that the $1 from the
subroutine won't clobber the $1 in the calling routine(s).  It's always
dangerous in any language to "read between the lines" of language
documentation (this is a major source of C portability problems).

The cure for your code is to test whether or not the match succeeded
directly, rather than testing a side effect!  Try:
    if( $zipin =~ /^\D*(\d{5})(\-(\d{4})|.*)/ )
instead of your current if test.

BTW, you don't need the return statement, and the regular expression
could be more economically written as:
    if( $zipin =~ /^\D*(\d{5})(-\d{4})?/ ) {
        $fullZip = $1 . $2;
    } ...
The only down side being that you'll get occasional warnings running
with -w when $2 isn't defined.

--Hal
Hal Wine <hal@dtor.com>     voice: 510/482-0597