我怎样才能让'='在Perl中调用一个复制构造函数?
How can I make '=' invoke a copy constructor in Perl?
我知道“=”不能在 Perl 中直接重载,但我希望能够使用“=”为我的对象之一调用复制构造函数。
示例:
my $object1 = Object->new('value' => 1);
# I want this to invoke the copy constructor of "$object1" instead of copying a reference
my $object2 = $object1;
# This should not modify "$object1"
$object2->set_value(12);
print $object1->get_value()."\n";
print $object2->get_value()."\n";
我希望输出为:
1
12
我怎样才能使这个工作?
要克隆数据,您可以使用 Clone 模块。
示例:
package Foo;
use parent 'Clone';
sub new { bless {}, shift }
package main;
my $obj = Foo->new;
my $copy = $obj->clone;
我知道“=”不能在 Perl 中直接重载,但我希望能够使用“=”为我的对象之一调用复制构造函数。
示例:
my $object1 = Object->new('value' => 1);
# I want this to invoke the copy constructor of "$object1" instead of copying a reference
my $object2 = $object1;
# This should not modify "$object1"
$object2->set_value(12);
print $object1->get_value()."\n";
print $object2->get_value()."\n";
我希望输出为:
1
12
我怎样才能使这个工作?
要克隆数据,您可以使用 Clone 模块。
示例:
package Foo;
use parent 'Clone';
sub new { bless {}, shift }
package main;
my $obj = Foo->new;
my $copy = $obj->clone;