如何对 Data::Dumper 的输出进行排序?
我想转储对象和散列的值,但它总是乱序打印键。如何按(递归)排序顺序转储键?
use Data::Dumper;
print Dumper $obj;
I want to dump the values of my object and hash, but it keeps printing the keys out of order. How can I dump the keys in (recursive) sort-order?
use Data::Dumper;
print Dumper $obj;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
设置
$Data::Dumper::Sortkeys = 1
以获取 Perl 的默认排序顺序。如果要自定义顺序,请将
$Data::Dumper::Sortkeys
设置为对子例程的引用,该子例程接收对散列的引用作为输入,并输出对散列列表的引用键按照您希望它们出现的顺序排列。Set
$Data::Dumper::Sortkeys = 1
to get Perl's default sort order.If you want to customize the order, set
$Data::Dumper::Sortkeys
to a reference to a subroutine that receives a reference to a hash as input, and outputs a reference to the list of the hash's keys in the order you want them to appear.对于不耐烦的人的简短回答
请使用 Data::Dumper::Concise 代替。它会对你的钥匙进行排序。像这样使用它:
为好奇的人提供更多单词
Data::Dumper::Concise 还为您提供更紧凑、更易于阅读的输出。
请注意,Data::Dumper::Concise 是 Data::Dumper 为您设置了合理的默认配置值。它相当于像这样使用 Data::Dumper:
Short answer for the impatient
Use Data::Dumper::Concise instead. It sorts your keys. Use it like this:
More words for the curious
Data::Dumper::Concise also gives you more compact, easier to read output.
Note that Data::Dumper::Concise is Data::Dumper with reasonable default configuration values set for you. Its equivalent to using Data::Dumper like this:
您可以将 $Data::Dumper::Sortkeys 变量设置为 true 值以获得默认排序:
或者在其中放置一个子例程以根据需要对键进行排序。
You can set the
$Data::Dumper::Sortkeys
variable to a true value to get a default sort:or put a subroutine in there to sort the keys however you want.
来自
Data::Dumper
文档:From the
Data::Dumper
documentation:对于那些在使用
Data::Dumper
打印时想要按值对 hashref 进行排序的人,这里有一个示例:这是一个更具可读性的替代方案,执行相同的操作,但是用一个变量来保存哈希值。它的效率较低,但对于较小的哈希值,有些人可能会发现它更好:
For those who want to sort a hashref by value when printing it with
Data::Dumper
, here is an example:And here is a more readable alternative, doing the same but with a variable to hold the hash. It's less efficient, but for small hashes, some may find it nicer:
对 ascii 和全数字进行排序:
sort ascii and full numeric: