Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
292 views
in Technique[技术] by (71.8m points)

hashref - How to set a list of scalars from a perl hash ref?

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
field2=$field2
field3=$field3
";
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)};

or like this:

my ($field1,$field2,$field3) = @$my_hash{qw(field1 field2 field3)};

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

Then we can get to your $my_hash hash-ref version by replacing the hash with a hash-ref in the usual way.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

1.4m articles

1.4m replys

5 comments

57.0k users

...