30

オブジェクトとハッシュの値をダンプしたいのですが、キーが順不同で表示され続けます。(再帰的な) ソート順でキーをダンプするにはどうすればよいですか?

use Data::Dumper;
print Dumper $obj;
4

6 に答える 6

56

$Data::Dumper::Sortkeys = 1Perl のデフォルトのソート順を取得するように設定します。順序をカスタマイズしたい場合は$Data::Dumper::Sortkeys、ハッシュへの参照を入力として受け取るサブルーチンへの参照に設定し、表示したい順序でハッシュのキーのリストへの参照を出力します。

# sort keys
$Data::Dumper::Sortkeys = 1;
print Dumper($obj);

# sort keys in reverse order - use either one
$Data::Dumper::Sortkeys = sub { [reverse sort keys %{$_[0]}] };
$Data::Dumper::Sortkeys = sub { [sort {$b cmp $a} keys %{$_[0]}] };
print Dumper($obj);
于 2011-09-19T05:40:54.613 に答える
13

せっかちな人への短い答え

代わりにData::Dumper::Conciseを使用してください。キーを並べ替えます。次のように使用します。

use Data::Dumper::Concise;

my $pantsToWear = {
    pony       => 'jeans',
    unicorn    => 'corduroy',
    marsupials => {kangaroo => 'overalls', koala => 'shorts + suspenders'},
};

warn Dumper($pantsToWear);

好奇心旺盛な人のためのより多くの言葉

Data :: Dumper :: Conciseは、よりコンパクトで読みやすい出力も提供します。

Data :: Dumper::ConciseData::Dumperであり、適切なデフォルト構成値が設定されていることに注意してください。次のようにData::Dumperを使用するのと同じです。

use Data::Dumper;
{
  local $Data::Dumper::Terse = 1;
  local $Data::Dumper::Indent = 1;
  local $Data::Dumper::Useqq = 1;
  local $Data::Dumper::Deparse = 1;
  local $Data::Dumper::Quotekeys = 0;
  local $Data::Dumper::Sortkeys = 1;
  warn Dumper($var);
}
于 2011-09-19T08:18:50.197 に答える
6

変数をtrue値に設定$Data::Dumper::Sortkeysして、デフォルトのソートを取得できます。

use Data::Dumper;
$Data::Dumper::Sortkeys  = 1;

my $hashref = {
    bob => 'weir',
    jerry =>, 'garcia',
    nested => {one => 'two', three => 'four'}};

print Dumper($hashref), "\n";

または、そこにサブルーチンを配置して、必要に応じてキーを並べ替えます。

于 2011-09-19T05:44:51.157 に答える
6

Data::Dumperドキュメントから:

$Data::Dumper::Sortkeys or $OBJ->Sortkeys([NEWVAL])
Can be set to a boolean value to control whether hash keys are dumped in sorted order. 
A true value will cause the keys of all hashes to be dumped in Perl's default sort order. 
Can also be set to a subroutine reference which will be called for each hash that is dumped. 
In  this case Data::Dumper will call the subroutine once for each hash, passing it the 
reference of the hash. The purpose of the subroutine is to return a reference to an array of 
the keys that will be dumped, in the order that they should be dumped. Using this feature, you 
can control both the order of the keys, and which keys are actually used. In other words, this 
subroutine acts as a filter by which you can exclude certain keys from being dumped. Default is  
0, which means that hash keys are not sorted.
于 2011-09-19T05:42:00.233 に答える