String 如何在perl中重载字符串
我试图在perl中将类重载为字符串。例如:String 如何在perl中重载字符串,string,perl,overloading,String,Perl,Overloading,我试图在perl中将类重载为字符串。例如: use MooseX::Declare; class overloadingInPerl{ use overload '""' => sub {shift->printOut()}; method printOut(){ return "Overloading worked"; } } my $overloadingTrial = overloadingInPerl->new(); pr
use MooseX::Declare;
class overloadingInPerl{
use overload '""' => sub {shift->printOut()};
method printOut(){
return "Overloading worked";
}
}
my $overloadingTrial = overloadingInPerl->new();
print $overloadingTrial;
打印输出:OverloadingPerl=HASH(0x1f520fc)
要打印:重载工作正常
有什么想法吗?使用重载
class overloadingInPerl is dirty {
使用重载
class overloadingInPerl is dirty {
除了添加@OylensPeegul所指出的
dirty
特性之外,您还可以通过将其名称作为字符串传递并从方法声明中删除()来删除调用实际函数的coderef
嗯,说起来容易,说起来难
#!/usr/bin/env perl
use Test::More tests=>1;
use MooseX::Declare;
class C is dirty {
use overload '""' => 'to_string';
method to_string { sprintf "#<%s data='%s'>", $self->meta->name, $self->data }
has data => (is=>'rw',default=>'');
}
is(C->new(data=>'hello'), "#<C data='hello'>");
#/usr/bin/env perl
使用测试::更多测试=>1;
使用MooseX::声明;
C类是脏的{
使用重载'''=>'到_字符串';
方法创建字符串{sprintf“#”,$self->meta->name,$self->data}
has data=>(is=>'rw',默认值=>'';
}
是(C->new(data=>'hello'),“#”号;
除了添加dirty
特性之外,正如@Oylenspeegul所指出的,您还可以删除调用实际函数的coderef,方法是将其名称作为字符串传递,并从方法声明中删除()
嗯,说起来容易,说起来难
#!/usr/bin/env perl
use Test::More tests=>1;
use MooseX::Declare;
class C is dirty {
use overload '""' => 'to_string';
method to_string { sprintf "#<%s data='%s'>", $self->meta->name, $self->data }
has data => (is=>'rw',default=>'');
}
is(C->new(data=>'hello'), "#<C data='hello'>");
#/usr/bin/env perl
使用测试::更多测试=>1;
使用MooseX::声明;
C类是脏的{
使用重载'''=>'到_字符串';
方法创建字符串{sprintf“#”,$self->meta->name,$self->data}
has data=>(is=>'rw',默认值=>'';
}
是(C->new(data=>'hello'),“#”号;