2010-10-02 39 views
2

我希望nstore是一個Perl哈希,它也包含一個代碼引用。在此之後perldoc我寫了這樣的事情:我應該如何在Perl中序列化代碼引用?

use strict; 
use warnings; 
local $Storable::Deparse = 1; 
my %hash = (... CODE => ...); 
nstore (\%hash, $file); 

我得到一個警告說Name "Storable::Deparse" used only once: possible typo at test4.pl line 15.。我想我可以專門壓制這個警告,但這讓我懷疑我是否做錯了什麼。

請注意此問題與此one有關。區分兩者的不同標題將是最受歡迎的。

回答

1

你忽視加載可存儲模塊,並設置其配置值的一個前。

use strict; 
use warnings; 
use Storable qw(nstore); 
local $Storable::Deparse = 1; 
my %hash = (... CODE => ...); 
nstore (\%hash, $file); 
1

代碼引用不能簡單地序列化。文件句柄,數據庫連接以及任何具有外部資源的內容不能簡單地序列化。

序列化這些項目時,必須以可重新創建它們的方式描述它們。例如,您可以將文件句柄序列化爲路徑,並將偏移量或代碼引用作爲引用指向的函數的名稱。

您可以找到子程序名代碼的參考點與Sub::Identify

#!/usr/bin/perl 

use strict; 
use warnings; 

use Sub::Identify qw/sub_fullname/; 

sub foo {} 

my $r = \&foo; 

print sub_fullname($r), "\n"; 

當然,這意味着你不能序列匿名引用和序列化的數據只能可靠地實現程序中使用以相同的方式命名的函數。

如果您發現自己需要這樣做,那麼最好使用類而不是簡單的代碼引用。

+0

+1謝謝。我終於決定改用一個對象。 – 2010-10-03 20:33:59

0

您還需要設置

$Storable::Eval = 1; 

這樣的:

#! perl 

use strict; 
use warnings; 

use Storable qw /nstore retrieve/; 


local $Storable::Deparse = 1; 
local $Storable::Eval = 1; 

my %hash = (CODE => sub {print "ahoj\n";}); 


nstore (\%hash, 'test'); 
my $retrieved = retrieve ('test'); 

$retrieved->{CODE}(); 
相關問題