alf*_*nso 5 perl hash perl-data-structures
我有一组可变大小的字符串,例如:
AAA23
AB1D1
A1BC
AAB212
我的目标是按字母顺序排列并为COLUMNS收集独特的字符,例如:
第一栏:AAAA
第二栏:AB1A
等等...
在这一刻,我能够通过散列哈希来提取帖子.但是现在,我该如何对数据进行排序?我可以为每个散列哈希创建一个新数组吗?
非常感谢你的帮助!
人
我的代码:
#!/usr/bin/perl
use strict;
use warnings;
my @sessions = (
"AAAA",
"AAAC",
"ABAB",
"ABAD"
);
my $length_max = 0;
my $length_tmp = 0;
my %columns;
foreach my $string (@sessions){
my $l = length($string);
if ($l > $length_tmp){
$length_max = $l;
}
}
print "max legth : $length_max\n\n";
my $n = 1;
foreach my $string (@sessions){
my @ch = split("",$string);
for my $col (1..$length_max){
$columns{$n}{$col} = $ch[$col-1];
}
$n++;
}
foreach my $col (keys %columns) {
print "colonna : $col\n";
my $deref = $columns{$col};
foreach my $pos (keys %$deref){
print " posizione : $pos --> $$deref{$pos}\n";
}
print "\n";
}
exit(0);
Run Code Online (Sandbox Code Playgroud)
你正在做的是旋转阵列。它不需要散列的散列或任何东西,只需要另一个数组。令人惊讶的是,List::Util 和 List::MoreUtils 都不提供一个。这是一个带有测试的简单实现。我猜想您想要用空格填充简短的条目,以便列显示正确。
#!/usr/bin/perl
use strict;
use warnings;
use Test::More;
use List::Util qw(max);
my @Things = qw(
AAA23
AB1D1
A1BC
AAB212
);
sub rotate {
my @rows = @_;
my $maxlength = max map { length $_ } @rows;
my @columns;
for my $row (@rows) {
my @chars = split //, $row;
for my $colnum (1..$maxlength) {
my $idx = $colnum - 1;
$columns[$idx] .= $chars[$idx] || ' ';
}
}
return @columns;
}
sub print_columns {
my @columns = @_;
for my $idx (0..$#columns) {
printf "Column %d: %s\n", $idx + 1, $columns[$idx];
}
}
sub test_rotate {
is_deeply [rotate @_], [
"AAAA",
"AB1A",
"A1BB",
"2DC2",
"31 1",
" 2",
];
}
test_rotate(@Things);
print_columns(@Things);
done_testing;
Run Code Online (Sandbox Code Playgroud)