首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何对Data::Dumper的输出进行排序?

如何对Data::Dumper的输出进行排序?
EN

Stack Overflow用户
提问于 2011-09-19 13:34:23
回答 4查看 17.3K关注 0票数 29

我想转储我的对象和散列的值,但它总是打乱键的打印顺序。如何以(递归的)排序顺序转储键?

代码语言:javascript
复制
use Data::Dumper;
print Dumper $obj;
EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2011-09-19 13:40:55

设置$Data::Dumper::Sortkeys = 1以获取Perl的默认排序顺序。如果要自定义顺序,请将$Data::Dumper::Sortkeys设置为对子例程的引用,该子例程接收对散列的引用作为输入,并按照希望散列键的出现顺序输出对散列键列表的引用。

代码语言:javascript
复制
# 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);
票数 55
EN

Stack Overflow用户

发布于 2011-09-19 13:42:00

Data::Dumper文档中:

代码语言:javascript
复制
$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.
票数 5
EN

Stack Overflow用户

发布于 2011-09-19 13:44:51

您可以将$Data::Dumper::Sortkeys变量设置为真值以获得默认排序:

代码语言:javascript
复制
use Data::Dumper;
$Data::Dumper::Sortkeys  = 1;

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

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

或者在其中放置一个子例程,以便随心所欲地对键进行排序。

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7466825

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档