简体   繁体   English

perl regex-将一行中的多个十进制数字转换为最接近的整数

[英]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: 我正在练习一个Perl正则表达式问题,其中有以下格式的行从stdin中读取:

I bought 2.3kg of oranges for $13.50. 我以13.50美元的价格购买了2.3公斤的橙子。

It takes 4.5 hours to get from the city to the sea. 从城市到大海需要4.5个小时。

She moved in 2010, and left in 2014. 她于2010年搬家,并于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. 我以$ 14.00的价格购买了2公斤的橙子。

It takes 5 hours to get from the city to the sea. 从城市到大海需要5个小时。

She moved in 2010, and left in 2014. 她于2010年搬家,并于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. 我的方法是将stdin中的所有行读入数组,然后对每行中的每个匹配项将十进制数替换为其最接近的整数。 I know you can round floating point numbers in Perl using the round() function. 我知道您可以使用round()函数在Perl中舍入浮点数。

However, using the round() function as the replacement text within the 's/(\\d+.?\\d*)//g' would not work. 但是,使用round()函数作为's /(\\ d +。?\\ d *)// g'中的替换文本将不起作用。 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. 使用s///e将代码作为替换表达式。 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.) (如果愿意,可以随意使用Math :: Round的round 。我只是用我熟悉的那个。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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