> -----Original Message-----
> From: John Edwards [mailto:[EMAIL PROTECTED]]
> Sent: Wednesday, November 21, 2001 5:46 AM
> To: 'WaspCatcher'; [EMAIL PROTECTED]
> Subject: RE: extracting *just* matched text
> 
> 
> Like this...
> 
> -- code --
> 
> my $text = "Hello 1234, come in";
> $text =~ /(\d{4,4})/;
> $match = $1 if $1;
> print $match;

Careful, this will cause problems if the regex doesn't match. Consider:

my $text = "Hello 1234, come in";
$text =~ /(\d{4,4})/;
$match = $1 if $1;
print $match;            # prints 1234
$text =~ /(foo)/;
$match = $1 if $1;
print $match;            # prints 1234 again!

$1 is left unchanged if the regex doesn't match. You need to test for this.

You can do this:

   print $1 if /(foo)/;

Or, you can take advantage of the fact that m// returns either the list
of matched expressions on success, or an empty list on failure and do:

   ($match) = /(foo)/;   # $match is undef on failure

-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to