Moose tips

Posted on September 13, 2011. Filed under: Uncategorized | Tags: , , , , |

init_arg – use alternate attribute name in new()

# in package Foo
has qw(bar is ro init_arg quux);
...
# elsewhere
my $foo = Foo->new( quux => 1 );

Foo has an attribute named “bar”, but we pass “quux” to the constructor.

See Moose::Manual::Attributes / Constructor parameters (init_arg)

init_arg – ban setting an attribute in new()

# in package Foo
has qw(bar is ro), init_arg => undef;
...
# elsewhere
my $foo = Foo->new( bar => 1 ); # dies

See Moose::Manual::Attributes / Constructor parameters (init_arg)

lazy_build

# in package Foo
has qw(bar is ro isa ArrayRef lazy_build 1);
# gets me:
#   lazy      => 1
#   builder   => '_build_bar',
#   clearer   => 'clear_bar',
#   predicate => 'has_bar',
...
sub _build_bar {
    my ($self, @args) = @_;
    ...
    return [ reverse @args ];
}

See Moose::Meta::Attribute

Native traits

Array

  • accessor($index)
  • accessor($index, $value)
  • clear
  • count
  • delete($index)
  • elements
  • first( sub { … } )
  • first_index( sub { … } )
  • get($index)
  • grep( sub { … } )
  • insert($index, $value)
  • is_empty
  • join($str)
  • map( sub { … } )
  • natatime($n)
  • natatime($n, $code)
  • pop
  • push($value, …)
  • reduce( sub { … } )
  • set($index, $value)
  • shallow_clone
  • shift
  • shuffle
  • sort( sub { … } )
  • sort
  • sort_in_place( sub { … } )
  • sort_in_place
  • splice($offs, $len, @values)
  • uniq
  • unshift($value, …)

Bool

Code

Counter

Has

Number

String

Liked it here?
Why not try sites on the blogroll...