10

在 Perl 5 中,如果我想查看哈希的内容,可以使用Data::ShowData::DumpData::Dumper.

例如:

use Data::Show;

my %title_for = (
    'Book 1' => {
        'Chapter 1' => 'Introduction',
        'Chapter 2' => 'Conclusion',
    },
    'Book 2' => {
        'Chapter 1' => 'Intro',
        'Chapter 2' => 'Interesting stuff',
        'Chapter 3' => 'Final words',
   }
);

show(%title_for);

哪个输出:

======(  %title_for  )======================[ 'temp.pl', line 15 ]======

    {
      "Book 1" => { "Chapter 1" => "Introduction", "Chapter 2" => "Conclusion" },
      "Book 2" => {
                    "Chapter 1" => "Intro",
                    "Chapter 2" => "Interesting stuff",
                    "Chapter 3" => "Final words",
                  },
    }

Perl 6 中有什么等价的吗?我想我记得 Damian Conway 在 YAPC 2010 上讨论过这个功能,但是我的笔记丢失了,谷歌搜索也没有帮助。

use v6;

my %title_for = (
  "Book 1" => { "Chapter 1" => "Introduction", "Chapter 2" => "Conclusion" },
  "Book 2" => {
                "Chapter 1" => "Intro",
                "Chapter 2" => "Interesting stuff",
                "Chapter 3" => "Final words",
              },
);

%title_for.say;

我发现最接近工作的是%title_for.say. 但是,嵌套哈希似乎很混乱:

Book 1 => Chapter 1 => Introduction, Chapter 2 => Conclusion, Book 2 => Chapter 1 => Intro, Chapter 2 => Interesting stuff, Chapter 3 => Final words

我正在使用从2015 年 1 月发布的 Rakudo Star开始在MoarVM上运行的 Perl6 。

4

3 回答 3

7

Perl6 文档似乎建议.perl在数据结构上使用,但看起来漂亮的打印需要额外的工作:

鉴于:

my @array_of_hashes = (
    { NAME => 'apple',   type => 'fruit' },
    { NAME => 'cabbage', type => 'no, please no' },
);

Perl 5

use Data::Dumper;
$Data::Dumper::Useqq = 1;
print Dumper \@array_of_hashes; # Note the backslash.

Perl 6

say @array_of_hashes.perl; # .perl on the array, not on its reference.
于 2015-02-17T16:31:30.177 回答
3

从那以后,我制作了一个可能很方便的PrettyDump模块:

use v6;
use PrettyDump;

my %title_for = (
  "Book 1" => { "Chapter 1" => "Introduction", "Chapter 2" => "Conclusion" },
  "Book 2" => {
                "Chapter 1" => "Intro",
                "Chapter 2" => "Interesting stuff",
                "Chapter 3" => "Final words",
              },
);

say PrettyDump.new.dump: %title_for;

带输出:

Hash={
    :Book 1(Hash={
        :Chapter 1("Introduction"),
        :Chapter 2("Conclusion")
    }),
    :Book 2(Hash={
        :Chapter 1("Intro"),
        :Chapter 2("Interesting stuff"),
        :Chapter 3("Final words")
    })
}

您也可以提供一些格式选项PrettyDump

于 2017-07-03T13:18:13.757 回答
2

dd用于 rakudo 中的数据转储。

my @array_of_hashes = (
    { NAME => 'apple',   type => 'fruit' },
    { NAME => 'cabbage', type => 'no, please no' },
);
dd @array_of_hashes;
于 2020-03-16T14:40:39.383 回答