题
我刚刚开始了解 领带.我有一个类命名的链接,我想这样做下列事情:
- 如果获取回报的链接地址
- 如果存储、储存的新地址
- 能够调用的方法上它
迄今为止,我的代码是:
package Link;
sub FETCH {
my $this = shift;
return $this->{"site"};
}
sub STORE {
my ($self,$site) = @_;
$self->{"site"} = $site;
}
sub print_method {
my $self = shift;
print $self->{"site"};
}
sub TIESCALAR {
my $class = shift;
my $link = shift;
my $this = {};
bless($this,$class);
$this->{"site"} = $link;
return $this;
}
1;
和代码,我在使用的检查功能是:
use Link;
tie my $var,"Link","http://somesite.com";
$var->print_method;
当然,脚本将终止与以下错误:不能调用的方法"print_method"没有一个包裹或物体在参考tietest.pl 线4。.
如果我理解它的消息正确, $var->print_method
解决了一些串的方法 print_method
被称为。我怎么可能从中受益的领带,但也使用变量,作为对象?
编辑:试验后一点,我发现,如果我回$自上取,我可以打电话的方法,但是,获取将不会返回的地址。
编辑2:perl僧侣供给我的解决方案: 绑 .绑会返回一个参考的对象变量。
通过组合捆绑我的方法,我可以完成我想要的一切。
解决方案
领带是错误的工具为这项工作。你用关系当你想要同样的接口,作为正常的数据类型,但要自定义如何行动做他们的工作。因为你想要访问和存储一串就像一个标已经不,领带不会为你做任何事情。
它看起来像是你想要的 URI 模块或一个子类,并且也许有些超载。
如果你真的需要这样做,你需要用正确的变量。的 领带 钩的可变指定为类指定,但它仍然是一个正常的标(而不是一个参考)。你必须使用目的的回报,如果你想叫的方法:
my $secret_object = tie my($normal_scalar), 'Tie::Class', @args;
$secret_object->print_method;
你也可以获得秘密的对象如果你只有绑标:
my $secret_object = tied $normal_scalar;
我有一整章上的配合 掌握Perl.
其他提示
我建议做一个正常的Perl对象然后 超载ing stringification.你失去了能力,储存的价值通过转让,但保留的能力,以获得的价值,通过印刷的对象。一旦你开始想要呼吁的方法,直接对象可能是你想要什么。
package Link;
use strict;
use Carp;
use overload
(
'""' => sub { shift->site },
fallback => 1,
);
sub new
{
my $class = shift;
my $self = bless {}, $class;
if(@_)
{
if(@_ == 1)
{
$self->{'site'} = shift;
}
else { croak "$class->new() expects a single URL argument" }
}
return $self;
}
sub site
{
my $self = shift;
$self->{'site'} = shift if(@_);
return $self->{'site'};
}
sub print_method
{
my $self = shift;
print $self->site, "\n";
}
1;
例的使用情况:
use Link;
my $link = Link->new('http://somesite.com');
print $link, "\n"; # http://somesite.com
$link->print_method; # http://somesite.com
如果你真的,真的想要分配工作太,你可以结合正常的对象超载stringification(Link
, 上)与 tie
:
package LinkTie;
use strict;
use Link;
sub FETCH
{
my $this = shift;
return $this->{'link'};
}
sub STORE
{
my($self, $site) = @_;
$self->{'link'}->site($site);
return $site;
}
# XXX: You could generalize this delegation with Class::Delegation or similar
sub print_method
{
my $self = shift;
print $self->{'link'}->print_method;
}
sub TIESCALAR
{
my $class = shift;
my $self = bless {}, $class;
$self->{'link'} = Link->new(@_);
return $self;
}
1;
例的使用情况:
tie my $link,'LinkTie','http://somesite.com';
print $link, "\n"; # http://somesite.com
$link->print_method; # http://somesite.com
$link = 'http://othersite.com';
print $link, "\n"; # http://othersite.com
$link->print_method; # http://othersite.com
这都是很丑陋的,并有很长的路要走刚刚得到的可疑能够分配到的东西,你也可以打电话的方法上和还打印。标准URI对象stringification可能是一个更好的选择。