简体   繁体   中英

perl regex - convert multiple decimal numbers on a line to nearest integer

I am practicing a Perl regex question where I have lines in the following format that are read in from stdin:

I bought 2.3kg of oranges for $13.50.

It takes 4.5 hours to get from the city to the sea.

She moved in 2010, and left in 2014.

And I have to convert all the decimal numbers in each line to their nearest integer. So the expected output would look like:

I bought 2kg of oranges for $14.00.

It takes 5 hours to get from the city to the sea.

She moved in 2010, and left in 2014.

I have the following code:

#!/usr/bin/perl -w
use strict;
use warnings;
use Math::Round;

my @lines = <STDIN>; 
chomp @lines;

foreach my $line (@lines) {
    $line =~ s/(\d+\.?\d*)/hello/g;
}

The part which I am not sure how to do is actually replace the decimal numbers in each line with their integer version. My approach is to read all the lines from stdin into an array, and then for each match on each line substitute the decimal number with its nearest whole number. I know you can round floating point numbers in Perl using the round() function.

However, using the round() function as the replacement text within the 's/(\\d+.?\\d*)//g' would not work. Using the substitution operator seemed to be the simplest approach, but I don't think I will be able to use it. I am not exactly sure what other methods I could use to solve this problem. Any insights would be really appreciated.

Use s///e to put code as the replacement expression. The code is expected to return the value to use as the replacement.

 s/(\d+\.\d+)/ sprintf("%.0f", $1) /eg

(Feel free to use Math::Round's round if you wish. I just used that with which I am familiar.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM