NAME
List::Objects::WithUtils::Role::Array - Array manipulation methods
SYNOPSIS
## Via List::Objects::WithUtils::Array ->
use List::Objects::WithUtils 'array';
my $array = array(qw/ a b c /);
$array->push(qw/ d e f /);
my @upper = $array->map(sub { uc })->all;
if ( $array->has_any(sub { $_ eq 'a' }) ) {
...
}
my $sum = array(1 .. 10)->reduce(sub { $_[0] + $_[1] });
# See below for full list of methods
## As a Role ->
use Role::Tiny::With;
with 'List::Objects::WithUtils::Role::Array';
DESCRIPTION
A Role::Tiny role defining methods for creating and manipulating ARRAY-type objects.
List::Objects::WithUtils::Array consumes this role (along with List::Objects::WithUtils::Role::WithJunctions) to provide array() object methods.
In addition to the methods documented below, these objects provide a TO_JSON
method exporting a plain ARRAY-type reference.
Basic array methods
new
Constructs a new ARRAY-type object.
copy
Creates a shallow clone of the current object.
count
Returns the number of elements in the array.
is_empty
Returns boolean true if the array is empty.
scalar
See "count".
Methods that manipulate the list
clear
Clears the array entirely.
delete
Splices a given index out of the array.
insert
$array->insert( $position, $value );
Inserts a value at a given position.
pop
Pops the last element off the array and returns it.
push
Pushes elements to the end of the array.
Returns the array object.
set
$array->set( $index, $value );
Takes an array element and a new value to set.
Returns the array object.
shift
Shifts the first element off the beginning of the array and returns it.
unshift
Adds elements to the beginning of the array.
Returns the array object.
splice
# 2-arg splice (remove elements):
my $spliced = $array->splice(0, 2)
# 3-arg splice (replace):
$array->splice(0, 1, 'abc');
Performs a splice()
on the current list and returns a new array object consisting of the items returned from the splice.
The existing array is modified in-place.
Methods that retrieve items
all
Returns all elements in the array as a plain list.
bisect
my ($true, $false) = array( 1 .. 10 )
->bisect(sub { $_[0] >= 5 })
->all;
my @bigger = $true->all; # ( 5 .. 10 )
my @smaller = $false->all; # ( 1 .. 4 )
Like "part", but creates an array-type object containing two partitions; the first contains all items for which the subroutine evaluates to true, the second contains the remaining items.
export
Same as "all"; included for consistency with hash-type objects.
flatten_all
Returns a plain list consisting of all sub-arrays recursively flattened.
get
Returns the array element corresponding to a specified index.
head
my ($first, $rest) = $array->head;
In list context, returns the first element of the list, and a new array-type object containing the remaining list. The original object's list is untouched.
In scalar context, returns just the first element of the array:
my $first = $array->head;
tail
Similar to "head", but returns either the last element and a new array-type object containing the remaining list (in list context), or just the last element of the list (in scalar context).
join
my $str = $array->join(' ');
Joins the array's elements and returns the joined string.
Defaults to ',' if no delimiter is specified.
mesh
my $meshed = array(qw/ a b c /)->mesh(
array( 1 .. 3 )
);
$meshed->all; # 'a', 1, 'b', 2, 'c', 3
Takes array references or objects and returns a new array object consisting of one element from each array, in turn, until all arrays have been traversed fully.
You can mix and match references and objects freely:
my $meshed = array(qw/ a b c /)->mesh(
array( 1 .. 3 ),
[ qw/ foo bar baz / ],
);
part
my $parts = array( 1 .. 8 )->part(sub { $i++ % 2 });
# Returns array objects:
$parts->get(0)->all; # 1, 3, 5, 7
$parts->get(1)->all; # 2, 4, 6, 8
Takes a subroutine that indicates into which partition each value should be placed.
Returns an array-type object containing partitions represented as array-type objects, as seen above.
Skipped partitions are empty array objects:
my $parts = array(qw/ foo bar /)->part(sub { 1 });
$parts->get(0)->is_empty; # true
$parts->get(1)->is_empty; # false
The subroutine is passed the value we are operating on:
array(qw/foo bar baz 1 2 3/)
->part(sub { $_[0] =~ /^[0-9]+$/ ? 0 : 1 })
->get(1)
->all; # 'foo', 'bar', 'baz'
reverse
Returns a new array object consisting of the reversed list of elements.
shuffle
my $shuffled = $array->shuffle;
Returns a new array object containing the shuffled list.
sliced
my $slice = $array->sliced(1, 3, 5);
Returns a new array object consisting of the elements retrived from the specified indexes.
Methods that find items
grep
my $matched = $array->grep(sub { $_[0] =~ /foo/ });
Returns a new array object consisting of the list of elements for which the given subroutine evaluated to true. $_[0]
is the element being operated on; you can also use the topicalizer $_
.
first
my $arr = array( qw/ ab bc bd de / );
my $first = $arr->first(sub { $_ =~ /^b/ }); ## 'bc'
Returns the first element of the list for which the given sub evaluates to true. $_
is set to each element, in turn, until a match is found (or we run out of possibles).
firstidx
Like "first", but return the index of the first successful match.
has_any
if ( $array->has_any(sub { $_ eq 'foo' }) ) {
...
}
If passed no arguments, returns the same thing as "count".
If passed a sub, returns boolean true if the sub is true for any element of the array; see "any" in List::MoreUtils.
$_
is set to the element being operated upon.
items_after
my $after = array( 1 .. 10 )->items_after(sub { $_ == 5 });
## $after contains [ 6, 7, 8, 9, 10 ]
Returns a new array object consisting of the elements of the original list that occur after the first position for which the given sub evaluates to true.
items_after_incl
Like "items_after", but include the item that evaluated to true.
items_before
The opposite of "items_after".
items_before_incl
The opposite of "items_after_incl".
Methods that iterate the list
map
my $lowercased = $array->map(sub { lc });
# Same as:
my $lowercased = $array->map(sub { lc $_[0] });
Evaluates a given subroutine for each element of the array, and returns a new array object. $_[0]
is the element being operated on; you can also use the topicalizer $_
.
natatime
my $iter = array( 1 .. 7 )->natatime(3);
$iter->(); ## ( 1, 2, 3 )
$iter->(); ## ( 4, 5, 6 )
$iter->(); ## ( 7 )
array( 1 .. 7 )->natatime(3, sub { my @vals = @_; ... });
Returns an iterator that, when called, produces a list containing the next 'n' items.
If given a coderef as a second argument, it will be called against each bundled group.
reduce
my $sum = array(1,2,3)->reduce(sub { $_[0] + $_[1] });
Reduces the array by calling the given subroutine for each element of the list. See "reduce" in List::Util.
Methods that sort the list
sort
my $sorted = $array->sort(sub { $_[0] cmp $_[1] });
Returns a new array object consisting of the list sorted by the given subroutine. $_[0]
and $_[1]
are equivalent to $a
and $b
in a normal sort() call.
sort_by
my $array = array(
{ id => 'a' },
{ id => 'c' },
{ id => 'b' },
);
my $sorted = $array->sort_by(sub { $_->{id} });
Returns a new array object consisting of the list of elements sorted via a stringy comparison using the given sub. See List::UtilsBy.
nsort_by
Like "sort_by", but using numerical comparison.
uniq
my $unique = $array->uniq;
Returns a new array object containing only unique elements from the original array.
uniq_by
my $array = array(
{ id => 'a' },
{ id => 'a' },
{ id => 'b' },
);
my $unique = $array->uniq_by(sub { $_->{id} });
Returns a new array object consisting of the list of elements for which the given sub returns unique values.
SEE ALSO
List::Objects::WithUtils::Array
List::Objects::WithUtils::Role::WithJunctions
AUTHOR
Jon Portnoy <avenj@cobaltirc.org>
Portions of this code are derived from Data::Perl by Matthew Phillips (CPAN: MATTP), haarg et al
Licensed under the same terms as Perl.