如何在Perl中打印哈希值,以便在每一行上打印3个键值对?
print %hash;
这将在一行中打印每个键值对。
答案 0 :(得分:3)
要显示哈希值,那么"在每行"上打印3 [n]个键值对,您可以使用计数器($n
)和%
(模数) op)确定何时打印" \n
"。演示:
use Modern::Perl;
my %h = ();
for (0..7) {
$h{$_} = chr(65 + $_);
}
print %h, "\n";
my $cols = +$ARGV[0] || 5;
my $n = -$cols;
for my $key (keys %h) {
print $key, ' => ', $h{$key}, 0 == ++$n % $cols ? "\n" : "\t\t";
}
print $n % $cols ? "\n------" : "------";
输出:
perl -w 31444449.pl 1
6G4E1B3D0A7H2C5F
6 => G
4 => E
1 => B
3 => D
0 => A
7 => H
2 => C
5 => F
------
perl -w 31444449.pl
6G4E1B3D0A7H2C5F
6 => G 4 => E 1 => B 3 => D 0 => A
7 => H 2 => C 5 => F
------
perl -w 31444449.pl 3
6G4E1B3D0A7H2C5F
6 => G 4 => E 1 => B
3 => D 0 => A 7 => H
2 => C 5 => F
------
然而,鲍罗丁的解决方案更简单。
请参阅mpapec answer以获得更改进的版本。
答案 1 :(得分:2)
一种非常简单的方法是将所有键和值复制到一个数组中,然后一次打印六(三对)
use strict;
use warnings;
my %h = map { $_ => 1 } 'A' .. 'H';
my @kv = %h;
while ( my @row = splice @kv, 0, 6 ) {
print "@row\n";
}
B 1 C 1 A 1
D 1 E 1 G 1
F 1 H 1
答案 2 :(得分:1)
您可以使用natatime from List::MoreUtils:
use List::MoreUtils qw/natatime/;
my $it = natatime 6, %ENV;
while (my @vals = $it->()) {
print "@vals\n";
}
List::MoreUtils
不在核心模块中,您需要安装它。
答案 3 :(得分:0)
全部谢谢。我试过这个并且有效。
my @keylist=sort keys %hash;
my $counter=0;
foreach(@keylist){
#printing the key value pairs
printf "%-15s :%3d ",$_,$hash{$_};
$counter++;
if($counter==3){
$counter=0;
print "\n";
}
}
print "\n";
答案 4 :(得分:-3)
如果您真的只想打印哈希值并检查调试值或进行分析,请使用
use Data::Dumper;
print Dumper(\%hash);
此打印哈希键和任意n个级别的值