Incrementing an attribute

xsawyerx on 2009-07-21T14:47:46

Isn't there anything better than this?

    $self->num( $self->num + 1 );

Anyone?


MX::AH

mattk on 2009-07-21T15:34:52

If you're using Moose, MooseX::AttributeHelpers has a Counter helper that will give you increment_num and decrement mutators:

use MooseX::AttributeHelpers;

has num => (
  metaclass => 'Counter',
  isa       => 'Num',
  is        => 'ro',
  provides  => {
    inc => 'inc_num',
    dec => 'dec_num',
    reset => 'reset_num',
  }
);

my $thing = Foo->new(num => 26);
$thing->inc_num;
$thing->inc_num;

Re:MX::AH

xsawyerx on 2009-07-21T15:41:53

Actually that is pretty good. Thanks!

in Rakudo/Perl6?

davegaramond on 2009-07-22T13:05:42

Makes me thankful there's Rakudo/Perl6, in which none of this is necessary.

Re:in Rakudo/Perl6?

xsawyerx on 2009-07-22T13:18:06

How would this be done in Perl6?

Re:in Rakudo/Perl6?

masak on 2009-10-14T14:22:19

$ perl6 -e 'class A { has $.attr is rw }; my $a = A.new(:attr(42)); $a.attr++; say $a.attr'
43