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

Re: [MacPerl] Setting a variable to a string match



On Fri, May 28, 1999 at 10:28:01AM -0700, Darryl Tang wrote:
> I'm trying to set a scalar variable to equal a string match.  For example,
> I want to extract a dollar amount (e.g., $23.99) from a line.  Here's what
> I've come up with so far:
> 
> 	$line =~ /\$(\d{0,}.\d\d)/; # apply a match to a line, using back
> reference parens
> 	$price = $1; # recall the last back reference
> 	print $price . "\n";
> 
> Is this the most efficient way to accomplish this task?  Seems like there
> should be a more efficient way.
> 

This way is subtly incorrect, because you did not test the success of the
match.  If the match failed, then $1 will still have its value from the
previous successful match.  Do this instead:

if ($line =~ /\$(\d*.\d\d)/) {   # \d{0,} === \d*
    $price = $1;
}

But you can also do it like this:

($price) = $line =~ /\$(\d*.\d\d)/;

In a list context, m// returns the list of captured subexpressions.


Ronald


===== Want to unsubscribe from this list?
===== Send mail with body "unsubscribe" to macperl-request@macperl.org