简体   繁体   English

如何在 Perl 中打印散列的内容?

[英]How can I print the contents of a hash in Perl?

I keep printing my hash as # of buckets / # allocated.我一直将我的哈希打印为 # of buckets / # allocated。 How do I print the contents of my hash?如何打印哈希的内容?

Without using a while loop would be most preferable (for example, a one-liner would be best).最好不要使用while循环(例如,最好使用单行代码)。

Data::Dumper is your friend. Data::Dumper是你的朋友。

use Data::Dumper;
my %hash = ('abc' => 123, 'def' => [4,5,6]);
print Dumper(\%hash);

will output将输出

$VAR1 = {
          'def' => [
                     4,
                     5,
                     6
                   ],
          'abc' => 123
        };

Easy:简单:

print "$_ $h{$_}\n" for (keys %h);

Elegant, but actually 30% slower (:):优雅,但实际上慢了 30% (:):

while (my ($k,$v)=each %h){print "$k $v\n"}

Here how you can print without using Data::Dumper在这里如何不使用Data::Dumper进行打印

print "@{[%hash]}";

For debugging purposes I will often use YAML .出于调试目的,我经常使用YAML

use strict;
use warnings;

use YAML;

my %variable = ('abc' => 123, 'def' => [4,5,6]);

print "# %variable\n", Dump \%variable;

Results in:结果是:

# %variable
---
abc: 123
def:
  - 4
  - 5
  - 6

Other times I will use Data::Dump .其他时候我会使用Data::Dump You don't need to set as many variables to get it to output it in a nice format than you do for Data::Dumper .Data::Dumper相比,您不需要设置那么多的变量来让它以更好的格式输出。

use Data::Dump = 'dump';

print dump(\%variable), "\n";
{ abc => 123, def => [4, 5, 6] }

More recently I have been using Data::Printer for debugging.最近我一直在使用Data::Printer进行调试。

use Data::Printer;
p %variable;
{
    abc   123,
    def   [
        [0] 4,
        [1] 5,
        [2] 6
    ]
}

( Result can be much more colorful on a terminal ) (结果在终端上可能会更加丰富多彩)

Unlike the other examples I have shown here, this one is designed explicitly to be for display purposes only.与我在此处展示的其他示例不同,此示例明确设计为仅用于显示目的。 Which shows up more easily if you dump out the structure of a tied variable or that of an object.如果您转储绑定变量或对象的结构,则更容易显示出来。

use strict;
use warnings;

use MTie::Hash;
use Data::Printer;

my $h = tie my %h, "Tie::StdHash";
@h{'a'..'d'}='A'..'D';
p %h;
print "\n";
p $h;
{
    a   "A",
    b   "B",
    c   "C",
    d   "D"
} (tied to Tie::StdHash)

Tie::StdHash  {
    public methods (9) : CLEAR, DELETE, EXISTS, FETCH, FIRSTKEY, NEXTKEY, SCALAR, STORE, TIEHASH
    private methods (0)
    internals: {
        a   "A",
        b   "B",
        c   "C",
        d   "D"
    }
}

The answer depends on what is in your hash.答案取决于您的哈希中的内容。 If you have a simple hash a simple如果你有一个简单的散列

print map { "$_ $h{$_}\n" } keys %h;

or要么

print "$_ $h{$_}\n" for keys %h;

will do, but if you have a hash that is populated with references you will something that can walk those references and produce a sensible output.会做,但是如果你有一个填充了引用的散列,你将得到一些可以遍历这些引用并产生合理输出的东西。 This walking of the references is normally called serialization.这种遍历引用通常称为序列化。 There are many modules that implement different styles, some of the more popular ones are:有许多模块实现了不同的风格,一些比较流行的是:

Due to the fact that Data::Dumper is part of the core Perl library, it is probably the most popular;由于Data::Dumper是核心 Perl 库的一部分,它可能是最流行的; however, some of the other modules have very good things to offer.但是,其他一些模块可以提供非常好的东西。

My favorite: Smart::Comments我的最爱: Smart::Comments

use Smart::Comments;
# ...

### %hash

That's it.而已。

Looping:循环:

foreach(keys %my_hash) { print "$_ / $my_hash{$_}\n"; }

Functional功能性

map {print "$_ / $my_hash{$_}\n"; } keys %my_hash;

But for sheer elegance, I'd have to choose wrang-wrang's.但是为了纯粹的优雅,我不得不选择wrang-wrang's。 For my own code, I'd choose my foreach.对于我自己的代码,我会选择我的 foreach。 Or tetro's Dumper use.或者tetro的Dumper使用。

If you want to be pedantic and keep it to one line (without use statements and shebang), then I'll sort of piggy back off of tetromino's answer and suggest:如果您想迂腐并将其保持在一行中(不使用 use 语句和 shebang),那么我会从 tetromino 的回答中抽身出来并建议:

print Dumper( { 'abc' => 123, 'def' => [4,5,6] } );

Not doing anything special other than using the anonymous hash to skip the temp variable;)除了使用匿名散列来跳过临时变量外,没有做任何特别的事情;)

The easiest way in my experiences is to just use Dumpvalue .根据我的经验,最简单的方法就是使用Dumpvalue

use Dumpvalue;
...
my %hash = { key => "value", foo => "bar" };
my $dumper = new DumpValue();
$dumper->dumpValue(\%hash);

Works like a charm and you don't have to worry about formatting the hash, as it outputs it like the Perl debugger does (great for debugging).像魅力一样工作,您不必担心格式化散列,因为它像 Perl 调试器一样输出它(非常适合调试)。 Plus, Dumpvalue is included with the stock set of Perl modules, so you don't have to mess with CPAN if you're behind some kind of draconian proxy (like I am at work).此外,Dumpvalue 包含在 Perl 模块的库存集中,因此如果您在某种严苛的代理后面(就像我在工作),您不必弄乱 CPAN。

I append one space for every element of the hash to see it well:我为散列的每个元素附加一个空格以便清楚地看到它:

print map {$_ . " "} %h, "\n";

I really like to sort the keys in one liner code:我真的很喜欢在一个线性代码中对键进行排序:

print "$_ => $my_hash{$_}\n" for (sort keys %my_hash);

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

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