如何从Perl哈希引用设置标量列表? [英] How to set a list of scalars from a perl hash ref?
本文介绍了如何从Perl哈希引用设置标量列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何从perl哈希中设置标量列表?
How do I set a list of scalars from a perl hash?
use strict;
my $my_hash = { field1=>'val1', field2=>'val2', field3=>'val3', };
my ($field1,$field2,$field3) = %{$my_hash}{qw(field1 field2 field3)};
print "field1=$field1\nfield2=$field2\nfield3=$field3\n";
推荐答案
您正在寻找散列片,在您的情况下,看起来像这样:
You're looking for a hash slice which in your case would look like this:
my ($field1,$field2,$field3) = @{$my_hash}{qw(field1 field2 field3)};
或类似这样:
my ($field1,$field2,$field3) = @$my_hash{qw(field1 field2 field3)};
如果我们简化一些事情,以便您使用的是直接哈希而不是hash-ref,则可以消除一些干扰,语法看起来会更清晰:
If we simplify things so that you're working with a straight hash rather than hash-ref, we can remove some of the noise and the syntax will look a bit clearer:
my %my_hash = ( field1=>'val1', field2=>'val2', field3=>'val3' );
my ($field1, $field2, $field3) = @my_hash{ qw(field1 field2 field3) };
# we want an array/list ---------^ ^ ^
# but my_hash is a hash -----------------/ |
# and we want these keys (in this order) ---/
# so we use a qw()-array
然后我们可以通过以通常的方式将哈希替换为哈希引用来获取您的$my_hash
哈希引用版本.
Then we can get to your $my_hash
hash-ref version by replacing the hash with a hash-ref in the usual way.
这篇关于如何从Perl哈希引用设置标量列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文