我有以下代碼:的Perl的grep沒有返回預期值
#!/usr/bin/perl
# splits.pl
use strict;
use warnings;
use diagnostics;
my $pivotfile = "myPath/Internal_Splits_Pivot.txt";
open PIVOTFILE, $pivotfile or die $!;
while (<PIVOTFILE>) { # loop through each line in file
next if ($. == 1); # skip first line (contains business segment code)
next if ($. == 2); # skip second line (contains transaction amount text)
my @fields = split('\t',$_); # split fields for line into an array
print scalar(grep $_, @fields), "\n";
}
鑑於在文本文件中的數據是這樣的:
4 G I M N U X
Transaction Amount Transaction Amount Transaction Amount Transaction Amount Transaction Amount Transaction Amount Transaction Amount
0000-13-I21 600
0001-8V-034BLA 2,172 2,172
0001-8V-191GYG 13,125 4,375
0001-9W-GH5B2A -2,967.09 2,967.09 25.00
我期望從Perl腳本的輸出爲:2 3 3 4
給出每行中定義元素的數量。該文件是一個帶有8列的製表符分隔的文本文件。
相反,我得到3 4 3 4
,我不知道爲什麼!
對於背景,我使用Counting array elements in Perl作爲我開發的基礎,因爲我正在計數行中元素的數量,以瞭解是否需要跳過該行。
+1幫助我記住'chomp'!也爲提供答案:) –
改變我的答案,因爲最終這是最能幫助我的! :)我發佈了一個答案,下面的解決方案爲我工作。 –