我有一个文件:
434462PW1 5
76252PPP8 5,714.79
76252PMB2 16,950.17
76252PRC5 25,079.70
76252PNY1 30,324.50
62630WCQ8 1.09
62630WCZ8 1.09
62630WBX4 36,731.90
62630WCQ8 1.07
62630WCZ8 1.07
76252PGB9 1.07
62630WBN6 1.07
62630WBA4 1.07
我需要去掉第二个值中的逗号,在第一个和第二个之间添加一个逗号。
434462PW1,5
76252PPP8,5714.79
76252PMB2,16950.17
76252PRC5,25079.70
76252PNY1,30324.50
62630WCQ8,1.09
62630WCZ8,1.09
62630WBX4,36731.90
62630WCQ8,1.07
62630WCZ8,1.07
76252PGB9,1.07
62630WBN6,1.07
62630WBA4,1.07
这是代码。我很难只剥离数值。
#!/usr/bin/perl
use strict ;
use warnings;
open my $handle, '<', "foofile";
chomp(my @positionArray = <$handle>);
foreach my $pos(@positionArray) {
if ($pos =~ /(w{9})s+(.*)/) {
if ($2=~/,/) {
my $without = $2=~s/,//g ;
print "$1,$withoutn";
}
}
}
由于逗号只出现在第二列,您可以简单地删除每行中的所有逗号。此外,由于空白仅存在于两列之间,因此可以用逗号替换所有空格。
foreach my $pos (@positionArray) {
$pos =~ s/,//g;
$pos =~ s/s+/,/;
print "$posn";
}
另一种方法是使用map
函数(输入和输出@
数组变量(来解决此问题。
chomp(my @positionArray = <$handle>);
my @out = map { $_=~s/,//g; $_=~s/s+/,/; $_; } @positionArray;
use Data::Dumper;
print Dumper @out;
由于无法解释的原因,您使代码比更复杂
use strict ;
use warnings;
use feature 'say';
my $filename = 'foofile';
open my $fh, '<', $filename
or die "Couldn't open $filename $!";
my @lines = <$fh>;
close $fh;
chomp @lines; # snip eol
for (@lines) {
my($id,$val) = split;
$val =~ s/,//; # modifier 'g' might be used if value goes beyond thousands
say "$id,$val";
}
输出
434462PW1,5
76252PPP8,5714.79
76252PMB2,16950.17
76252PRC5,25079.70
76252PNY1,30324.50
62630WCQ8,1.09
62630WCZ8,1.09
62630WBX4,36731.90
62630WCQ8,1.07
62630WCZ8,1.07
76252PGB9,1.07
62630WBN6,1.07
62630WBA4,1.07