如何编辑Perl哈希转储中的某些值?

问题描述 投票:0回答:1

假设我有这些哈希:

my $hash1 = {
  firstname => 'john',
  lastname => 'doe',
};

my $hash2_nested = {
  name => {
    firstname => 'jean',
    lastname => 'doe',
  }
};

注意:哈希值可以嵌套x倍。

我想使用Data :: Dumper,可以在其中打印这些哈希值的副本,但具有隐藏的姓氏。意味着,它应该打印出来:

$VAR1 = {
           'firstname' => 'john'
           'lastname' => '***',
        };
and this:
$VAR1 = {
          'name' => {
                      'firstname' => 'john'
                      'lastname' => '***',
                    }
        };

是否有任何Perl库在其中递归搜索哈希键并动态替换其值?类似于:

replace_hash_value($hash1, 'lastname', '***');
perl hash
1个回答
0
投票

为什么不自己编写此类子例程?

use strict;
use warnings;
use feature 'say';

my $hash1 = {
    firstname => 'john',
    lastname => 'doe'
};

my $hash2_nested = {
    name => {
        firstname => 'jean',
        lastname => 'doe'
    }
};

my $mask = 'lastname';

hash_mask($hash1,$mask);
hash_mask($hash2_nested,$mask);

sub hash_mask {
    say "\$VAR = {";
    hash_mask_x(shift, shift, 1);
    say "};";
}

sub hash_mask_x {
    my $hash   = shift;
    my $mask_k = shift;
    my $depth  = shift;

    my $indent = ' ' x 8;
    my $space  = $indent x $depth;

    while( my($k,$v) = each %{$hash} ) {
        if (ref $v eq 'HASH') {
            say $space . "$k => {";
            hash_mask_x($v,$mask_k,$depth+1);
            say $space . "}";
        } elsif( $k eq $mask_k ) {
            say $space . "'$k' => '*****'";
        } else {
            say $space . "'$k' => '$v'";
        }
    }
}

输出

$VAR = {
        'lastname' => '*****'
        'firstname' => 'john'
};
$VAR = {
        name => {
                'lastname' => '*****'
                'firstname' => 'jean'
        }
};
© www.soinside.com 2019 - 2024. All rights reserved.