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

Re: [MacPerl] $1 issues



On Fri, 9 Feb 1996, yeah wrote:

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

I think the problem is that when the match fails, $1 (and $2 - $9) are 
just not created.  It is probably a bug that you get the value of the 
previous match.  However, if you test to see if the match was successful 
in the first place, you can avoid the issue. In a scalar context, /.../ 
returns a 1 if the match is successful.  Then you can be assured that $1, 
etc. have the values from the current match.

> 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

Change those last two lines to:

    if ($zipin =~ /^\D*(\d{5})(\-(\d{4})|.*)/)

>        {
>         print "[matched on $1] ";
>         $mainzip=$1;
>         $tail = "-" . $3 if ($3);
>         $fullzip = $tail ? $mainzip . $tail : $mainzip;
>         }
>     else { $fullzip = 0; }
>     return $fullzip;
>     }

John Peterson -- University Networking Services -- Brigham Young University
Internet: John_Peterson@byu.edu                       Phone: (801) 378-5007