如何查看特定的哈希键以更改其值?

Pau*_*kov 4 debugging perl tie

我有一个哈希,例如$hash->{'foo'}{'bar'}.

我想Carp::cluckbar密钥值发生变化的任何地方打电话.

怎么做 ?在CPAN上有没有可以做到这一点的现成模块?

ike*_*ami 6

my $hash = { foo => { bar => 1 } };
Internals::SvREADONLY( $hash->{foo}{bar}, 1 );
$hash->{foo}{bar} = 2;
Run Code Online (Sandbox Code Playgroud)

产生

Modification of a read-only value attempted at -e line 4.
Run Code Online (Sandbox Code Playgroud)

但这是一个致命的错误,它不包括跟踪(除非使用Carp :: Always).

我建议在标量中添加set magic.

use Carp            qw( cluck );
use Variable::Magic qw( wizard cast );

my $wizard = wizard(
   set => sub {
      cluck("Warning: Modification of a read-only value attempted");
   },
);

my $hash = { foo => { bar => 1 } };
cast( $hash->{foo}{bar}, $wizard );
$hash->{foo}{bar} = 2;
Run Code Online (Sandbox Code Playgroud)

产生

Warning: Modification of a read-only value attempted at -e line 6.
        main::__ANON__(SCALAR(0x4200c90), undef) called at -e line 12
        eval {...} called at -e line 12
Run Code Online (Sandbox Code Playgroud)

同样可以实现tie,但它会更昂贵.(绑定变量建立在magic.)