我想转储我的对象和散列的值,但它总是打乱键的打印顺序。如何以(递归的)排序顺序转储键?
use Data::Dumper;
print Dumper $obj;
发布于 2011-09-19 13:40:55
设置$Data::Dumper::Sortkeys = 1
以获取Perl的默认排序顺序。如果要自定义顺序,请将$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-19 13:42:00
从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-19 13:44:51
您可以将$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";
或者在其中放置一个子例程,以便随心所欲地对键进行排序。
https://stackoverflow.com/questions/7466825
复制相似问题