首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么Storable会加载一些类,而不是其他类?

为什么Storable会加载一些类,而不是其他类?
EN

Stack Overflow用户
提问于 2013-04-20 09:53:21
回答 2查看 234关注 0票数 3

我在Storable中遇到了冻结对象的问题。当Storable解冻一个对象时,它应该加载这个类。这通常是正确的,但有时并非如此。

代码语言:javascript
复制
#!/usr/bin/env perl -l

use strict;
use warnings;

use Storable;

if( fork ) {
}
else {
    print "In child.";

    # Load modules in a child process so the parent does not have them loaded
    require Foo;
    print $INC{"Foo.pm"};
    print $Foo::VERSION;
    Storable::store( Foo->new("http://example.com"), "/tmp/tb2.out" );

    require DateTime;
    print $INC{"DateTime.pm"};
    Storable::store( DateTime->new(year => 2009), "/tmp/uri.out" );

    exit;
}

wait;

print "Child is done.";
print "------------------------------";

print "DateTime is not loaded" if !$INC{"DateTime.pm"};
my $datetime = Storable::retrieve("/tmp/uri.out");
print $INC{"DateTime.pm"};
print $datetime->year;

print "Foo is not loaded" if !$INC{"Foo.pm"};
my $obj = Storable::retrieve("/tmp/tb2.out");
print $INC{"Foo.pm"};
print $obj->id;

和非常简单的Foo.pm。

代码语言:javascript
复制
$ cat lib/Foo.pm 
package Foo;

use strict;
use vars qw($VERSION);
$VERSION = "1.60";

sub new {
    my $class = shift;

    return bless { foo => 23 }, $class;
}

sub id { 42 }

1;

我从那个项目中得到了..。

代码语言:javascript
复制
In child.
lib/Foo.pm
1.60
/Users/schwern/perl5/perlbrew/perls/perl-5.16.2-threads/lib/site_perl/5.16.2/darwin-thread-multi-2level/DateTime.pm
Child is done.
------------------------------
DateTime is not loaded
/Users/schwern/perl5/perlbrew/perls/perl-5.16.2-threads/lib/site_perl/5.16.2/darwin-thread-multi-2level/DateTime.pm
2009
Foo is not loaded
Use of uninitialized value in print at /Users/schwern/tmp/test.plx line 38.

Can't locate object method "id" via package "Foo" at /Users/schwern/tmp/test.plx line 39.

正如您所看到的,它将愉快地加载DateTime,但不会加载我的Foo模块。对象已恢复,但未加载Foo.pm。我在Storable2.34和perl 5.16.2中遇到了这个问题。

人们会重复这个问题吗?有解决方案吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-20 10:27:01

DateTime定义了STORABLE_freezeSTORABLE_thaw。我们可以推断出,如果类使用了钩子来冻结自己,并寻找相应的钩子来解冻它,则可以推断出可存储的注释。模块加载是钩子逻辑的一部分,Foo不调用钩子逻辑。

票数 3
EN

Stack Overflow用户

发布于 2013-04-21 00:46:32

你可以一直这样做

代码语言:javascript
复制
my $class = ref $obj;
eval "require $class";

不确定您看到的DateTime的bevavior是否是DateTime的可存储钩子的结果,但是您不需要钩子来需要模块。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16115714

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档