使用列表哈希,我如何以随机顺序对每个键/列表元素进行操作?

sir*_*ato 1 algorithm perl

例如,如果我的HoL看起来像:

%HoL = ( 
    "flintstones"        => [ "fred", "barney" ],
    "jetsons"            => [ "george", "jane", "elroy" ],
    "simpsons"           => [ "homer", "marge", "bart" ],
);
Run Code Online (Sandbox Code Playgroud)

我想创建一个循环,允许我以完全随机的顺序在每个键/元素对上操作一次(这样它也可以随机地在键之间跳转,而不仅仅是元素),我该怎么做?我认为它会使用shuffle,但搞清楚细节会打败我.

(抱歉没有问题;我没有编码很长时间.我也无法通过谷歌搜索找到这个特定问题的答案,不过我敢说它之前曾在某处得到过回答.)

cjm*_*cjm 6

构建一个包含所有键值对的数组,然后将其洗牌:

use List::Util 'shuffle';

my %HoL = (
    "flintstones"        => [ "fred", "barney" ],
    "jetsons"            => [ "george", "jane", "elroy" ],
    "simpsons"           => [ "homer", "marge", "bart" ],
);

# Build an array of arrayrefs ($ref->[0] is the key and $ref->[1] is the value)
my @ArrayOfPairs = map {
  my $key = $_;
  map { [ $key, $_ ] } @{$HoL{$key}}
} keys %HoL;


for my $pair (shuffle @ArrayOfPairs) {
  print "$pair->[1] $pair->[0]\n";
}
Run Code Online (Sandbox Code Playgroud)