我在perl脚本中有一个排序数组,例如:
qw(aaa bbb ccc ddd eee fff ggg hhh iii jjj kkk lll)
>前三分之一在左栏
>中间三分之一在中间栏
>并且最后三分之一在右栏
aaa eee iii bbb fff jjj ccc ggg kkk ddd hhh lll
我一直试图使用模数,但它变得越来越复杂,并认为可能有一个优雅的解决方案.最终我打算将它用于类似于bash中的select.
谢谢.
解决方法
use List::MoreUtils qw( part ); my $num_rows = int(@a/3); my @aoa = map [ @a[@$_] ],part { $_ % $num_rows } 0..$#a; print("@$_\n") for @aoa;
要么
use List::MoreUtils qw( part ); my $num_rows = int(@a/3); my @aoa = part { $_ % $num_rows } 0..$#a; print("@a[ @$_ ]\n") for @aoa;
要么
my $num_rows = int(@a/3); for my $row_num (0..$num_rows-1) { print("@a[ map { $row_num + $num_rows*$_ } 0..2 ]\n"); }
以上版本不假设@a%3 == 0.
use List::MoreUtils qw( part ); use POSIX qw( ceil ); my $num_rows = ceil(@a/3); my @aoa = map [ @a[@$_] ],part { $_ % $num_rows } 0..$#a; print("@$_\n") for @aoa;
要么
use List::MoreUtils qw( part ); use POSIX qw( ceil ); my $num_rows = ceil(@a/3); my @aoa = part { $_ % $num_rows } 0..$#a; print("@a[ @$_ ]\n") for @aoa;
要么
use POSIX qw( ceil ); my $num_rows = ceil(@a/3); for my $row_num (0..$num_rows-1) { print("@a[ grep { $_ < @a } map { $row_num + $num_rows*$_ } 0..2 ]\n"); }