2010-09-16 21 views
3

我使用Hash::Utillock_keys無論何時嘗試訪問散列中不存在的密鑰。如何提高Perl中lock_keys的使用率?

  1. 有時我的散列很深(散列散列值爲散列 ...)。有沒有一種快速方法可以一次全部鎖定它們?

  2. 是否有可能控制在故障 默認消息(即 添加散列的轉儲,其中鍵沒有被發現)

回答

1
  1. lock_hash_recurse

  2. 捕捉異常,然後根據需要轉儲並重新拋出。


use Try::Tiny; 
try { 
    $hash{key} = 123; # illegal modification 
} catch { 
    use DDS; DumpLex \%hash; 
    die $_; 
} 
+0

你將不得不每包哈希查找,這可能是不可行的。 – 2010-09-16 10:54:33

+0

'使用Hash :: Util qw(lock_hash_recurse unlock_hash_recurse)'給我''lock_hash_recurse'不被Hash :: Util模塊導出「unlock_hash_recurse」不被Hash :: Util模塊導出??? – 2010-09-16 13:38:40

+0

該功能不可導出。說全名:'Hash :: Util :: lock_hash_recurse ...' – daxim 2010-09-16 13:47:20

1

問題2是可能的,但你在哈希::的Util作者本人的率性:

#!/usr/bin/perl 

use strict; 
use warnings; 

use Hash::Util qw/lock_keys/; 

$SIG{__DIE__} = sub { 
    my $message = shift; 
    return unless my ($key, $file, $line) = $message =~ m{ 
     Attempt [ ] to [ ] access [ ] disallowed [ ] key [ ] '(.*?)' 
     [ ] in [ ] a [ ] restricted [ ] hash [ ] at [ ] (.*?) [ ] 
     line [ ] (.*?). 
    }x; 
    die "$key doesn't exist at $file line $line.\n"; 
}; 

my %h = map { $_ => undef } "a" .. "z"; 
lock_keys %h; 

my $s = $h{4};