in reply to Zipcode Regex Help

I need a false value returned if the zip code doesn't match, 1 returned if the 1st 5 digits match, and a 2 if all 9 digits match.

How about something like this?

sub zipMatch { my $zip_card = shift; return 0 unless $zip_card =~ m/\b(\d{5})(?:-(\d{4}))?/b/; return 1 unless $2; return 2; }
The \b are to avoid accidentally matching an invalid zipcode like
0000000000-0000000000

Replies are listed 'Best First'.
Re: Re: Zipcode Regex Help
by tcf22 (Priest) on Jun 25, 2003 at 21:31 UTC
    I have something similiar to your code that is working now. I'm just curious, why the regex I was using isn't working the way the I expected.
      Because that's not how the return value of matches is defined. In scalar context, a succesful match returns the number of times it matched. Without the /g, this will always be 1. With /g, this might be more, but that wouldn't help in your case. An unsuccesful match in scalar context returns the empty string, regardless of any flags.

      That's the way how it works, and if you want to have different values depending what matched, you need to do a little more work.

      Abigail