简体   繁体   中英

How do I use Perl to process and print an array in chunks?

How do I print array in chunks and specify how many elements per line to print?

#Given    
@array = qw/a b c d e f g i j/;
$chr_per_line =3;

Output:

a b c \n
d e f \n
g i j \n

Thanks!

Rather than using a destructive splice for this kind of thing I prefer using natatime (N at a time) from List::MoreUtils

use List::MoreUtils 'natatime';

my @array = qw/a b c d e f g i j/;
my $iter = natatime 3, @array;

while( my @chunk = $iter->() ) { 
    print join( ' ', @chunk ), "\n";
}

Use splice :

while (@array) {
    print join " ", splice(@array, 0, $chr_per_line), "\n";
}

List::MoreUtils::natatime

use strict;
use warnings;
use List::MoreUtils qw(natatime);

my @array = qw/a b c d e f g i j/;
my $it = natatime(3, @array);
while (my @vals = $it->()) {
    print "@vals\n";
}

__END__
a b c
d e f
g i j

This is one of many list tasks that I have addressed in my module List::Gen

use List::Gen 'every';

my @array = qw(a b c d e f g h i);

print "@$_\n" for every 3 => @array;

which prints:

a b c
d e f
g h i

Unlike natatime , the slices here remain aliased to the source list:

$$_[0] = uc $$_[0] for every 3 => @array;

print "@array\n"; # 'A b c D e f G h i'

The splice solution can also be written:

while ( my @chunk = splice(@array, 0, $chr_per_line) ) {
    print join( ' ', @chunk, "\n" );
}

which can be more convenient if you need to do more than one thing in the loop.

This works too

use strict;  
use warnings;   

my @array = qw/a b c d e f g i j/;  
my $chr_per_line =3;  

for (my ($i,$k)=(0,0); ($k+=$chr_per_line)<=@array; $i=$k) {  
   print "@array[$i .. $k-1] \n";  
}    

__END__  

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM