On 04/21/2015 10:37 PM, mt1957 wrote:
L.s.

The following piece of code shows that one must be careful using my or
state variables in a class. They have the same behavior as an our
variable if I am right.

The difference is that 'our'-variables can be accessed from the outside ($A::p), 'my' and 'state'-varaibles can't.

The difference between 'my' and 'state' is that 'state' retains its state (sic) between several executions of the block, but since a class block is only executed once (while it's compiled), the distinction is moot here.

Are they all kind of global to the class/object?
---
class A {

   my $a;
   has $.a;
   our $p;
   state $q;

   method set ($b) {
     $a = $b;
     $!a = $b+10;
     $p = $b+20;
     $q = $b+30;
   }

   method get {
     $!a //= 'undefined';
     return "my=$a, has=$!a, our=$p, state=$q";
   }
}

my $x = A.new;
$x.set(2);        # Set variables in x object
say "X: ", $x.get;

my $y = A.new;
say "Y: ", $y.get;      # Only attribute undefined
$y.set(4);            # Set variables in y object
say "X: ", $x.get;     # Modified in $x except for the attribute
---


The results are;

X: my=2, has=12, our=22, state=32
Y: my=2, has=undefined, our=22, state=32
X: my=4, has=12, our=24, state=34

Only the attribute is kept local to the object but all other variables
are shared between $x and $y.

Should one use only attributes in a class and use our variables to share
between objects?

If you want per-object local storage, use attributes, yes.

Cheers,
Moritz

Reply via email to