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. 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?


Reply via email to