如何打印在特定的顺序一个Perl哈希? [英] How can I print a Perl hash in specific order?

查看:610
本文介绍了如何打印在特定的顺序一个Perl哈希?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的code

#!/usr/bin/perl
use strict;

my @a = ("b","a","d","c");
my %h = ("a",1,"b",2,"c",3,"d",4);

#print '"' . join('","', @a), "\"\n";

print "\n";
foreach my $key (@a) {
    print '"' . $h{$key} . '",';
}
print "\n";

这是输出

"2","1","4","3",

但我想,它只是输出

but I would like that it just outputted

"2","1","4","3"

请注意,最后的,是不存在的。

Notice that last ',' isn't there.

是否有可能如打印哈希以特定的顺序,或一些其他的手段来得到输出我想要什么?

Is it possible to e.g. print a hash in a specific order, or some other trick to get the output I want?

更新:

根据friedo的答案,我能得到它的权利。

Based on friedo's answer I was able to get it right.

print '"' . join('","', @h{@a}), "\"\n";

Friedo的回答没有周围的值引号。

Friedo's answer doesn't have the quotes around the values.

推荐答案

您可以使用 hash切片以得到的值,然后用加入与逗号粘在一起他们。

You can use a hash slice to get the values, then use join to stick them together with commas.

print join ",", @h{@a};

这篇关于如何打印在特定的顺序一个Perl哈希?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆