开发者

group list of numbers

I have a list of numbers in a file in one column such as-

144

542

123

54

234

233

I want to group numbers every nth time For example : if n=2 then 144,542 is in one group , 123,54 in the second , 234,233 is in the third till the end of the file

the loop I wrote just gives me the first group of numbers and not the entire list: What changes should I do ?

use strict;
open ( IN ,"$inputfile") || die ("ca开发者_开发技巧nnot open ! ");
my @list;
my $N=2;
while (@list = <IN>) {
chomp;
for ( $i=1;$i<=$N;$i++){
print "@list[$i]";
}
}


Use natatime from List::MoreUtils

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

Prints:

144 542
123 54
234 233


You can use the by function from List::Gen to partition a list into equal size segments:

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

which prints:

144 542
123 54
234 233


I have to applaud your use of strict and would like to encourage you to also add warnings. :)

And a solution that makes the semantics a bit more clear:

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜