在不同的perl对象之间共享数据

时间:2011-11-04 06:59:27

标签: perl perl-module perl-data-structures

如果我有一个数据成员在perl类(Myclass)中说“dt”。我创建了类的两个对象说“obj1”和“obj2”。我使用obj1设置“dt”为“2”。如果我通过“obj2”访问“dt”,我应该将“dt”的值设为2。

 use Myclass;

 my $obj1 = new Myclass;
 my $obj2 = new Myclass;

 $obj1->{dt} = 2;

 print $obj2->{dt}; // This should print "2"

如何实现类来实现这个?

1 个答案:

答案 0 :(得分:1)

使用our关键字,该关键字具有包范围:

package Myclass;

use strict;
use warnings;

our $dt;

sub new {
    my $class = shift;
    my $self = {};
    bless $self, $class
}

sub dt { # Implement getter/setter

    shift;              # Pulls object off @_ (ignores calling class)
    $dt = shift if @_;  # If argument provided, sets 'dt' to it
    return $dt;         # In both cases (getter/setter), returns current $dt
}

1;

然后:

use strict;
use warnings;
use feature 'say';
use Myclass;


my $obj1 = Myclass->new;
my $obj2 = Myclass->new;

$obj1->dt( 2 );  # Set to 2 via $obj1

say $obj2->dt;   # '2'

$obj2->dt( 5 );  # Set to 5 via $obj2

say $obj1->dt;   # '5'