我在一列文件中有一个数字列表,例如 -
144
542
123
54
234
233
我想每隔第n次对数字进行分组
例如:如果n = 2,那么144,542在一个组中,123,54在第二组中,234,233在第三组中直到文件末尾
我写的循环只给了我第一组数字,而不是整个列表:
我应该做些什么改变?
use strict;
open ( IN ,"$inputfile") || die ("cannot open ! ");
my @list;
my $N=2;
while (@list = <IN>) {
chomp;
for ( $i=1;$i<=$N;$i++){
print "@list[$i]";
}
}
答案 0 :(得分:3)
natatime
use warnings;
use strict;
use List::MoreUtils qw(natatime);
my $n = 2;
my @list;
while (<DATA>) {
chomp;
push @list, $_;
}
my $it = natatime($n, @list);
while (my @vals = $it->()) {
print "@vals\n";
}
__DATA__
144
542
123
54
234
233
打印:
144 542
123 54
234 233
答案 1 :(得分:2)
您可以使用List::Gen中的by
功能将列表划分为相同大小的细分:
use List::Gen qw(by);
my $pairs = by 2 => # partition by 2
grep {s/^\s+|\s+$//g; length} # remove whitespace and empty lines
<DATA>; # read all lines
print "@$_\n" for @$pairs;
__DATA__
144
542
123
54
234
233
打印:
144 542 123 54 234 233
答案 2 :(得分:1)
我要赞美你对strict的使用,并鼓励你也添加警告。 :)
一种使语义更清晰的解决方案:
use strict;
use warnings;
use File::Slurp 'read_file';
use Array::Split qw( split_by );
my $inputfile = 'file';
my @lines = read_file( "$inputfile" );
$_ =~ s/[\r\n]//g for @lines; # remove newlines
my @grouped_lines = split_by( 2, @lines );
for my $group ( @grouped_lines ) {
print join ',', @{$group};
print "\n";
}
__END__
144
542
123
54
234
233
becomes:
144,542
123,54
234,233