qod*_*nja 26 sorting perl data-dump
我想将我的对象的值转储到我的浏览器中,但它会不按顺序打印密钥.如何在(递归)排序顺序中转储密钥?
use Data::Dumper;
print Dumper $obj;
Run Code Online (Sandbox Code Playgroud)
soc*_*pet 45
设置$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);
Run Code Online (Sandbox Code Playgroud)
Eri*_*son 11
请改用Data :: Dumper :: Concise.它排序你的钥匙.像这样使用它:
use Data::Dumper::Concise;
my $pantsToWear = {
pony => 'jeans',
unicorn => 'corduroy',
marsupials => {kangaroo => 'overalls', koala => 'shorts + suspenders'},
};
warn Dumper($pantsToWear);
Run Code Online (Sandbox Code Playgroud)
Data :: Dumper :: Concise还为您提供更紧凑,更易读的输出.
请注意,Data :: Dumper :: Concise 是 Data :: 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);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
从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.
Run Code Online (Sandbox Code Playgroud)
您可以将$Data::Dumper::Sortkeys变量设置为true值以获得默认排序:
use Data::Dumper;
$Data::Dumper::Sortkeys = 1;
my $hashref = {
bob => 'weir',
jerry =>, 'garcia',
nested => {one => 'two', three => 'four'}};
print Dumper($hashref), "\n";
Run Code Online (Sandbox Code Playgroud)
或在其中放置子例程以对键进行任意排序。
| 归档时间: |
|
| 查看次数: |
14053 次 |
| 最近记录: |