如何使用perl删除文件中可用的最后一行。
我的数据如下。
"A",1,-2,-1,-4,
"B",3,-5,-2.-5,
如何删除最后一行...我正在对所有数字求和,但在最后收到一个空值。
尝试使用chomp,但没有工作。
以下是当前使用的代码:
while (<data>) {
chomp(my @row = (split ',' , $_ , -1);
say sum @row[1 .. $#row];
}
试试这个(外壳单行(:
perl -lne '!eof() and print' file
或作为脚本的一部分:
while (defined($_ = readline ARGV)) {
print $_ unless eof();
}
您应该使用 Text::CSV
或 Text::CSV_XS
来处理逗号分隔值文件。 这些模块在 CPAN 上可用。 这种类型的解决方案如下所示:
use Text::CSV;
use List::Util qw(sum);
my $csv = Text::CSV->new({binary => 1})
or die "Cannot use CSV: " . Text::CSV->error_diag;
while(my $row = $csv->getline($fh)) {
next unless ($row->[0] || '') =~ m/w/; # Reject rows that don't start with an identifier.
my $sum = sum(@$row[1..$#$row]);
print "$sumn";
}
如果您遇到不使用正确 CSV 解析器的解决方案,那么至少您需要将其添加到现有的 while 循环中,紧跟在 chomp 之后:
next unless scalar(@row) && length $row[0]; # Skip empty rows.
这一行的要点是检测一行何时为空 - 没有元素,或者在 chomp 之后元素为空。
我怀疑这是一个 X/Y 问题。你认为你想避免处理输入中的最后一行(空?(,而实际上你应该确保所有输入数据都是你期望的格式。
您可以采取多种措施来检查数据的有效性。
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use List::Util 'sum';
use Scalar::Util 'looks_like_number';
while (<DATA>) {
# Chomp the input before splitting it.
chomp;
# Remove the -1 from your call to split().
# This automatically removes any empty trailing fields.
my @row = split /,/;
# Skip lines that are empty.
# 1/ Ensure there is data in @row.
# 2/ Ensure at least one element in @row contains
# non-whitespace data.
next unless @row and grep { /S/ } @row;
# Ensure that all of the data you pass to sum()
# looks like numbers.
say sum grep { looks_like_number $_ } @row[1 .. $#row];
}
__DATA__
"A",1.2,-1.5,4.2,1.4,
"B",2.6,-.50,-1.6,0.3,-1.3,