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

心已入冬 提交于 2020-01-30 08:03:40

问题


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";

回答1:


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.




回答2:


The following works just fine:

#!/usr/bin/perl
use warnings;
use strict;
my $my_hash = { field1=>'val1', field2=>'val2', field3=>'val3', };
my ($field1,$field2,$field3) = (values %{$my_hash});
print "field1=$field1\nfield2=$field2\nfield3=$field3\n";

but, see the following for why it won't work well:

Is Perl guaranteed to return consistently-ordered hash keys?

An example of this going wrong is as follows:

my $my_hash = { field1=>'val1', blah=>'val1.1', field2=>'val2', field3=>'val3', };
my ($field1,$field2, $blah,$field3) = (sort values %{$my_hash});
print "field1=$field1\nfield2=$field2\nblah=$blah\nfield3=$field3\n";

the output is:

field1=val1
field2=val1.1
blah=val2
field3=val3

Note that the value of $field1 is wrong here. As "mu is too short" has already noted a Hash Slice is the way to go here to make sure the ordering is what you expect, and don't forget to use warnings on all your code.



来源:https://stackoverflow.com/questions/13657103/how-to-set-a-list-of-scalars-from-a-perl-hash-ref

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!