Search code examples
regexperlscalarslurp

Weird perl behavior. Slurp versus an assignment


I ran across something strange in perl that I thought I'd share. I have a text file called "testfile.txt".

Here it is....

BLAH BLAH BLAH BLAH BLAH
The dollar amount is $2.30 today
BLAH BLAH BLAH BLAH BLAH

Now I want to extract the 2.30. In my example below, I am slurping the file and it works fine. The second way it doesn't work at all. Is there some magic in the slurp?

#!/usr/local/bin/perl

## THIS WORKS
my $content;
my $filename = "testfile.txt";
my $fh="FILEIN";
open(my $fh, '<', $filename) or die "cannot open file $filename";
{
   local $/;
   $content = <$fh>;
}
close($fh);
my $price;
($price)=$content=~m{is\s\$([0-9]{1,2}\.[0-9]{2})\stoday};
print "Result is $price\n"; #Correctly produces 2.30

## DOESN'T WORK

$content2="BLAH BLAH BLAH BLAH BLAH The dollar amount is $2.30 today BLAH BLAH BLAH BLAH BLAH";
my $price2;
($price2)=$content2=~m{is\s\$([0-9]{1,2}\.[0-9]{2})\stoday};
print "Result is $price2\n"; #Doesn't work

NOTE: (Clarification). How would I extract 2.30 from the assignment example? In my real world application, that's where I am being stumped. Anyone have an idea how I'd extract that?
JW


Solution

  • $content2="BLAH BLAH BLAH BLAH BLAH The dollar amount is $2.30 today BLAH BLAH BLAH BLAH BLAH"
    

    Since the string is in double quotes, the $2 is replaced by the value of the Perl variable $2 - which is the contents of the second parenthesized subexpression of the last regular expression match, but what's important is that it's not what you want. Use single quotes instead:

    $content2='BLAH BLAH BLAH BLAH BLAH The dollar amount is $2.30 today BLAH BLAH BLAH BLAH BLAH'