如何按照插入顺序将哈希值提取到数组中?
给定 Perl 中的散列(任何散列),如何按照添加顺序从该散列中提取值并将它们放入数组中?
示例:
my %given = ( foo => '10', bar => '20', baz => '15' );
我想得到以下结果:
my @givenValues = (10, 20, 15);
Given a hash in Perl (any hash), how can I extract the values from that hash, in the order which they were added and put them in an array?
Example:
my %given = ( foo => '10', bar => '20', baz => '15' );
I want to get the following result:
my @givenValues = (10, 20, 15);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
来自
perldoc perlfaq4
:如何让我的哈希记住我将元素放入其中的顺序?From
perldoc perlfaq4
: How can I make my hash remember the order I put elements into it?以下将执行您想要的操作:
注意:更好的解决方案是使用 Tie::IxHash 或 Tie::Hash::Indexed 到保存器插入顺序。
The following will do what you want:
NB: An even better solution is to use Tie::IxHash or Tie::Hash::Indexed to preserver insertion order.
如果您有一个顺序正确的键列表,则可以使用哈希切片:
否则,请使用
Tie::IxHash
。If you have a list of keys in the right order, you can use a hash slice:
Otherwise, use
Tie::IxHash
.您可以使用
values
,但我认为您无法按正确的顺序获取它们,因为在创建哈希时顺序已经丢失You can use
values
, but I think you can't get them in the right order , as the order has been already lost when you created the hash