Search code examples
perlperl-moduleperl-data-structures

Sharing data between different perl objects


If I have a data member say "dt" in a perl class (Myclass). I have created two objects of the class say "obj1" and "obj2". I set "dt" using obj1 as "2". If I access "dt" through "obj2", I should get the value of "dt" as 2.

 use Myclass;

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

 $obj1->{dt} = 2;

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

How to implement the class to achieve this??


Solution

  • Use the our keyword, which will have package scope:

    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;
    

    And then:

    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'