Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: $1 don't reset (non loop)

by snowcrash (Friar)
on Feb 17, 2004 at 11:20 UTC ( [id://329561]=note: print w/replies, xml ) Need Help??


in reply to $1 don't reset (non loop)

from the perlre manpage: The numbered variables ($1, $2, $3, etc.) and the related punctuation set ("$+", "$&", "$`", and "$'") are all dynamically scoped until the end of the enclosing block or until the next successful match, whichever comes first.

So $1 is only set if the match succeeds, that's why it's a good idea to write
if ($adress1 =~ /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/) { $adress1 = $1; } if ($adress2 =~ /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/) { $adress2 = $1; }

snowcrash

Replies are listed 'Best First'.
Re: Re: $1 don't reset (non loop)
by Skeeve (Parson) on Feb 17, 2004 at 11:35 UTC
    If I see it right, you didn't get it quite correct. $addressX should become undef if no match. So this should work:
    if ($adress1 =~ /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/) { $adress1 = $1; } else { $adress1 = undef; } # and so on...
    which should be reducable to:
    Which is not, as you'll see below, reducable to:
    { $adress1 =~ /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/) $adress1 = $1; } { $adress2 =~ /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/) $adress2 = $1; }
    Update: Thanks to Abigail-II who found out my mistake.
      No, not really. That only works if $1 happens to be undefined. Which you can't count on. Watch:
      #!/usr/bin/perl use strict; use warnings; "meep" =~ /(.*)/; # Set $1. my $address1 = "Tsjakka"; # Will match. my $address2 = "Tsjakka!"; # Will not match. { $address1 =~ /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/; $address1 = $1; } { $address2 =~ /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/; $address2 = $1; } print $address1, "\n"; print $address2, "\n"; __END__ Tsjakka meep
      $address2 doesn't become undef. The solution is much simpler. The regex will either match the entire string, or there's no match. So, we could just do:
      /^([A-Za-z0-9öäåÖÄÅ][A-Za-zöäåÖÄÅ0-9\s\-\.\,]*)$/ or $_ = undef for $address1, $address2;

      Abigail

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://329561]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (8)
As of 2024-04-19 07:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found