我有一個包含嵌套鍵/值對,哈希引用和/或數組引用的哈希引用。Perl:將哈希引用(例如Dumper的輸出)格式化爲字符串
我想數據::自卸車的結果模擬成一個字符串,但:
- 刪除鍵「報價」。
- 刪除結構中的空白(但不包含值)
- 獎勵:按字母順序排序鍵。
- 獎金獎金:首先打印鍵/值對,然後是哈希引用,然後是數組引用。
例如:
#!/usr/bin/perl -w
use strict;
use warnings;
use Data::Dumper;
my $hash_ref = {
'private' => {
'locked' => 'FALSE',
'allowedAuth' => 'Digest'
},
'profile' => 'Default',
'id' => '123456',
'privacy' => 'FALSE',
'public' => [
{
'allowed' => 'FALSE',
'configured' => {
'profileId' => 'hello world'
},
'isDefault' => 'TRUE',
'maxSessions' => '3'
},
{
'isDefault' => 'FALSE',
'privateId' => '[email protected]',
'maxSessions' => '3',
'allowed' => 'FALSE',
'implicit' => '1',
}
],
'indicator' => 'FALSE'
};
print STDERR Dumper ($hash_ref);
理想情況下,我想輸出是:
my $str = "id=>'123456',indicator=>'FALSE',profile=>'Default',privacy=>'FALSE',private=>{allowedAuth=>'Digest',locked=>'FALSE'},public=>[{allowed=>'FALSE',configured=>{profileId=>'hello world'},isDefault=>'TRUE',maxSessions=>'3'},{allowed=>'FALSE',implicit=>'1',isDefault=>'FALSE',maxSessions=>'3',privateId=>'[email protected]'}]";
我已嘗試遞歸函數;然而,我不知道如何擺脫最後的逗號(特別是散列引用 - 對於數組ref,我可以使用索引並檢查它是否是最後一個)。另外,排序鍵似乎太難了。
sub recHash
{
my ($hash_ref) = @_;
my $response = "";
for my $k (keys %$hash_ref) {
my $v = $hash_ref->{$k};
if (ref($v) eq "HASH") {
$response .= "$k=>{" . recHash($v) . "}"; # recurse through the hash references.
}
elsif (ref($v) eq "ARRAY") {
$response .= "$k=>[";
# recurse through the array references.
foreach my $item (@$v) {
$response .= "{".recHash($item)."},";
}
$response .= "],";
return $response;
}
else {
$response .= "$k=>'$v',";
}
}
return $response;
}
print recHash($hash_ref);
我的輸出是(我認爲這是有缺陷的,當我繼續運行它):
private=>{allowedAuth=>'Digest',locked=>'FALSE',}profile=>'Default',id=>'123456',indicator=>'FALSE',privacy=>'FALSE',public=>[{configured=>{profileId=>'hello world',}maxSessions=>'3',allowed=>'FALSE',isDefault=>'TRUE',},{allowed=>'FALSE',maxSessions=>'3',implicit=>'1',privateId=>'[email protected]',isDefault=>'FALSE',},],