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

[MacPerl] $1 issues




Funny how $1 seems like just a bit more than $.99 when it's taken out
of context, eh? At least that's true in America.

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!

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...

Below is a quick hack that illustrates my problem... and some sample output.
I'd appreciate any insight regarding what I'm doing wrong.

Of course, if there is an easy way to force $1 to be flushed -- that is,
to set the scope of the life of $1, then that would probably work.

Thanks.
--
matt.


#!perl

# using MacPerl 4.1.8

# accepts any input; returns either 0 or 99999 / 99999-9999 string
# (valid US ZIP codes take the form 99999 or 99999-9999)

while (<STDIN>)
   {
    chop($in = $_);
    if ($in eq "quit") { exit; }
    print "$in --> ";
    $out = &valid_zip($in);
    print $out, "\n";
    }

1;

sub valid_zip
   {
    local($zipin) = @_;
    local($tail,$fullzip,$mainzip);
    $zipin =~ /^\D*(\d{5})(\-(\d{4})|.*)/;
    if ($1) # if a string of 5+ digits are found, take the first 5
       {
        print "[matched on $1] ";
        $mainzip=$1;
        $tail = "-" . $3 if ($3);
        $fullzip = $tail ? $mainzip . $tail : $mainzip;
        }
    else { $fullzip = 0; }
    return $fullzip;
    }


OUTPUT
------
123
123 --> 0                            # not enough digits
12345
12345 --> [matched on 12345] 12345   # OK. string of 5 digits
123
123 --> [matched on 12345] 12345     # why did this match?!
                                     # expected result is 0