Reputation: 53
I'm probably just missing something simple but the s///
isn't assigning the changed string to my variable. I try a more simple s///
and it does work.
This example should trim the any digits after the decimal if there are more than three.
my $price = 12.34567;
print "$price\n";
$price =~ s/(\.\d\d[1-9]?)d*/$1/;
print "$1\n"; # This is printing .345 correctly.
print "$price\n"; # This should be 12.345 but is unchanged.
my $story = "dog";
$story =~ s/(do)g/$1/;
print "$story\n"; # This works. It's changed to "do"
Edit: If the third digit is a zero it should trim it after two digits.
"Prettifying a stock Price: ...always take the first two digits after the decimal point, and take the third digit only if it is not zero. Then, remove any other digits.
Upvotes: 3
Views: 105
Reputation: 30971
Indeed, you missed only a backslash before the last "d".
Change the first substiturion instruction to:
$price =~ s/(\.\d\d[1-9]?)\d*/$1/;
Upvotes: 0
Reputation: 126722
Your substitution is wrong.
$price =~ s/(\.\d\d[1-9]?)d*/$1/;
should be
$price =~ s/(\.\d\d[1-9]?)\d*/$1/;
Your own version matches because d*
can match an empty string, which it does because there are no d
characters after the third decimal place
It seems odd to insist that any third decimal digit must be non-zero. So 0.00
is fine, but 0.000
is not, and will be truncated to the former. Is that what you intended?
Upvotes: 1