| MouseX::NativeTraits::ArrayRef(3pm) | User Contributed Perl Documentation | MouseX::NativeTraits::ArrayRef(3pm) |
MouseX::NativeTraits::ArrayRef - Helper trait for ArrayRef attributes
package Stuff;
use Mouse;
has 'options' => (
traits => ['Array'],
is => 'ro',
isa => 'ArrayRef[Str]',
default => sub { [] },
handles => {
all_options => 'elements',
add_option => 'push',
map_options => 'map',
filter_options => 'grep',
find_option => 'first',
get_option => 'get',
join_options => 'join',
count_options => 'count',
has_options => 'count',
has_no_options => 'is_empty',
sorted_options => 'sort',
},
);
This module provides an Array attribute which provides a number of array operations.
These methods are implemented in MouseX::NativeTraits::MethodProvider::ArrayRef.
$stuff = Stuff->new;
$stuff->options(["foo", "bar", "baz", "boo"]);
my $count = $stuff->count_options;
print "$count\n"; # prints 4
$stuff->has_no_options ? die "No options!\n" : print "Good boy.\n";
my @option = $stuff->all_options;
print "@options\n"; # prints "foo bar baz boo"
my $option = $stuff->get_option(1);
print "$option\n"; # prints "bar"
my $found = $stuff->find_option( sub { /^b/ } );
print "$found\n"; # prints "bar"
my @found = $stuff->filter_options( sub { /^b/ } );
print "@found\n"; # prints "bar baz boo"
my @mod_options = $stuff->map_options( sub { $_ . "-tag" } );
print "@mod_options\n"; # prints "foo-tag bar-tag baz-tag boo-tag"
my $found = $stuff->reduce_options( sub { $_[0] . $_[1] } );
print "$found\n"; # prints "foobarbazboo"
You can provide an optional subroutine reference to sort with (as you can with Perl's core "sort" function). However, instead of using $a and $b, you will need to use $_[0] and $_[1] instead.
# ascending ASCIIbetical
my @sorted = $stuff->sort_options();
# Descending alphabetical order
my @sorted_options = $stuff->sort_options( sub { lc $_[1] cmp lc $_[0] } );
print "@sorted_options\n"; # prints "foo boo baz bar"
You can provide an optional subroutine reference to sort with (as you can with Perl's core "sort" function). However, instead of using $a and $b, you will need to use $_[0] and $_[1] instead.
This is equivalent to "sort(sub{ by($_[0]) cmp by($_[1]) })", but implemented effectively.
Currently (as of Moose 0.98) this is a Mouse specific method.
This is equivalent to "sort_in_place(sub{ by($_[0]) cmp by($_[1]) })", but implemented effectively.
Currently (as of Moose 0.98) this is a Mouse specific method.
my $joined = $stuff->join_options( ':' );
print "$joined\n"; # prints "foo:bar:baz:boo"
Currently (as of Moose 0.98) this is a Mouse specific method.
Currently (as of Moose 0.98) this is a Mouse specific method.
MouseX::NativeTraits
| 2022-06-16 | perl v5.34.0 |