我如何在 Perl6 中查看散列的内容(以类似于 Perl 5 模块 Data::Dump 或 Data::Show 的方式)?

How can I view the contents of a hash in Perl6 (in a fashion similar to the Perl 5 modules Data::Dump or Data::Show)?

在 Perl 5 中,如果我想查看散列的内容,我可以使用 Data::Show, Data::Dump, or Data::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

我在 MoarVM from the January 2015 release of Rakudo Star 上使用 Perl6 运行。

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

Given:

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.

此后我制作了一个 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 提供一些格式设置选项。

dd 用于 rakudo 中的数据转储。

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