简体   繁体   English

如何按特定顺序打印Perl哈希?

[英]How can I print a Perl hash in specific order?

I have this 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";

that outputs 那个输出

"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 eg print a hash in a specific order, or some other trick to get the output I want? 是否有可能以特定顺序打印哈希,或者其他一些技巧来获得我想要的输出?

Update: 更新:

Based on friedo's answer I was able to get it right. 基于friedo的回答,我能够做到对了。

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

Friedo's answer doesn't have the quotes around the values. 弗里多的答案没有关于价值观的引用。

print join("," => map qq["$_"], @h{@a}), "\n";

At the heart of this line is @h{@a} , a hash slice that means the same as 这一行的核心是@h{@a} ,一个哈希切片 ,意思相同

($h{"b"}, $h{"a"}, $h{"d"}, $h{"c"})

The obvious advantage is economy of expression. 明显的优势是表达的经济性。

Moving out one level, we find the map operator: for each value from @h{@a} , wrap it in double quotes using qq["$_"] . 移出一个级别,我们找到map运算符:对于@h{@a}每个值,使用qq["$_"]将其@h{@a}双引号。 Because you want double quotes in the result, the code uses qq// to switch delimiters. 因为您希望结果中有双引号,所以代码使用qq//来切换分隔符。 Otherwise, you'd be stuck with "\\"$_\\"" or a concatenation chain as in your question. 否则,你会遇到问题中的"\\"$_\\""或连接链。

Finally, join inserts commas between the mapped values. 最后, join在映射值之间插入逗号。 In this case, => is identical to the comma operator, but I use it here instead of 在这种情况下, =>与逗号运算符相同,但我在这里使用它而不是

join(",", ...)

which I find visually unpleasing because of the commas being crammed together. 由于逗号被挤在一起,我觉得这看起来很不愉快。

You may be tempted to write the join without parentheses, but doing so would make "\\n" an argument to join rather than print . 您可能想要在没有括号的情况下编写join ,但这样做会使"\\n"成为join而不是print的参数。

您可以使用哈希切片来获取值,然后使用join将它们与逗号结合在一起。

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

使用join在值之间放置逗号而不是在末尾,并map以用双引号包装每个值。

print join(",", map { qq|"$h{$_}"| } @a);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM