从散列中的数组中获取随机元素

dma*_*rra -2 arrays random perl

我在google上看到了很多关于如何获得随机数组索引的结果,但是我无法将它应用于这种情况.

考虑以下:

my %hash;
my @array = {"foo", "bar", "poo"};

$hash->{mykey} = @array;
Run Code Online (Sandbox Code Playgroud)

如何从$ hash - > {mykey}中的数组中获取随机元素?类似下面的代码不起作用:

my $element = $hash->{mykey}[rand($hash->{mykey})];
Run Code Online (Sandbox Code Playgroud)

编辑:所以下面的答案非常有用.特别是我的问题更复杂的是我正在使用线程模块,完全忘了共享我附加到哈希元素的数组!因此,答案对我来说不起作用.

在确定了这种疏忽后,下面的解决方案完美无缺.

ike*_*ami 6

三个错误.


1.以下创建一个包含一个元素的数组,一个对哈希的引用:

my @array = {"foo", "bar", "poo"};
Run Code Online (Sandbox Code Playgroud)

你肯定打算使用

my @array = ("foo", "bar", "poo");
Run Code Online (Sandbox Code Playgroud)

2.

$hash->{mykey} = @array;
Run Code Online (Sandbox Code Playgroud)

是一样的

$hash->{mykey} = 3;
Run Code Online (Sandbox Code Playgroud)

您不能将数组存储在标量中,但可以存储对标量的引用.

$hash->{mykey} = \@array;
Run Code Online (Sandbox Code Playgroud)

它会的

rand(@a)    # rand conveniently imposes a scalar context.
Run Code Online (Sandbox Code Playgroud)

对于数组,所以它是

rand(@{ $ref })
Run Code Online (Sandbox Code Playgroud)

用于引用数组.这意味着您需要以下内容:

my $element = $hash->{mykey}[ rand(@{ $hash->{mykey} }) ];
Run Code Online (Sandbox Code Playgroud)

或者你可以把它分成两行.

my $array = $hash->{mykey};
my $element = $array->[ rand(@$array) ];
Run Code Online (Sandbox Code Playgroud)

总之,我们有以下几点:

my @array = ( "foo", "bar", "poo" );
my $hash = { mykey => \@array };

my $element = $hash->{mykey}[ rand(@{ $hash->{mykey} }) ];
Run Code Online (Sandbox Code Playgroud)

  • @ysth,我很困惑为什么你会提到这一点,但我看到其他评论中提到了线程.没有什么是简单的`lock @ $ array;`无法处理. (2认同)