NAME

Sub::HandlesVia::HandlerLibrary::Array - library of array-related methods

SYNOPSIS

package My::Class {
  use Moo;
  use Sub::HandlesVia;
  use Types::Standard 'ArrayRef';
  has attr => (
    is => 'rwp',
    isa => ArrayRef,
    handles_via => 'Array',
    handles => {
      'my_accessor' => 'accessor',
      'my_all' => 'all',
      'my_all_true' => 'all_true',
      'my_any' => 'any',
      'my_apply' => 'apply',
      'my_clear' => 'clear',
      'my_count' => 'count',
      'my_delete' => 'delete',
      'my_elements' => 'elements',
      'my_first' => 'first',
      'my_first_index' => 'first_index',
      'my_flatten' => 'flatten',
      'my_flatten_deep' => 'flatten_deep',
      'my_for_each' => 'for_each',
      'my_for_each_pair' => 'for_each_pair',
      'my_get' => 'get',
      'my_grep' => 'grep',
      'my_head' => 'head',
      'my_insert' => 'insert',
      'my_is_empty' => 'is_empty',
      'my_join' => 'join',
      'my_map' => 'map',
      'my_max' => 'max',
      'my_maxstr' => 'maxstr',
      'my_min' => 'min',
      'my_minstr' => 'minstr',
      'my_natatime' => 'natatime',
      'my_not_all_true' => 'not_all_true',
      'my_pairfirst' => 'pairfirst',
      'my_pairgrep' => 'pairgrep',
      'my_pairkeys' => 'pairkeys',
      'my_pairmap' => 'pairmap',
      'my_pairs' => 'pairs',
      'my_pairvalues' => 'pairvalues',
      'my_pick_random' => 'pick_random',
      'my_pop' => 'pop',
      'my_print' => 'print',
      'my_product' => 'product',
      'my_push' => 'push',
      'my_reduce' => 'reduce',
      'my_reductions' => 'reductions',
      'my_reset' => 'reset',
      'my_reverse' => 'reverse',
      'my_sample' => 'sample',
      'my_set' => 'set',
      'my_shallow_clone' => 'shallow_clone',
      'my_shift' => 'shift',
      'my_shuffle' => 'shuffle',
      'my_shuffle_in_place' => 'shuffle_in_place',
      'my_sort' => 'sort',
      'my_sort_in_place' => 'sort_in_place',
      'my_splice' => 'splice',
      'my_sum' => 'sum',
      'my_tail' => 'tail',
      'my_uniq' => 'uniq',
      'my_uniq_in_place' => 'uniq_in_place',
      'my_uniqnum' => 'uniqnum',
      'my_uniqnum_in_place' => 'uniqnum_in_place',
      'my_uniqstr' => 'uniqstr',
      'my_uniqstr_in_place' => 'uniqstr_in_place',
      'my_unshift' => 'unshift',
    },
  );
}

DESCRIPTION

This is a library of methods for Sub::HandlesVia.

DELEGATABLE METHODS

accessor( $index, $value? )

Arguments: Int, Optional[Any].

Acts like get if given one argument, or set if given two arguments.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
$object->my_accessor( 1, 'quux' );
say Dumper( $object->attr ); ## ==> [ 'foo', 'quux', 'baz' ]
say $object->my_accessor( 2 ); ## ==> 'baz'

all()

All elements in the array, in list context.

my $object = My::Class->new( attr => [ 'foo', 'bar' ] );
my @list = $object->my_all;
say Dumper( \@list ); ## ==> [ 'foo', 'bar' ]

all_true( $coderef )

Arguments: CodeRef.

Like List::Util::all().

any( $coderef )

Arguments: CodeRef.

Like List::Util::any().

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
my $truth  = $object->my_any( sub { /a/ } );
say $truth; ## ==> true

apply( $coderef )

Arguments: CodeRef.

Executes the coderef (which should modify $_) against each element of the array; returns the resulting array in list context.

clear()

Empties the array.

my $object = My::Class->new( attr => [ 'foo' ] );
$object->my_clear;
say Dumper( $object->attr ); ## ==> []

count()

The number of elements in the referenced array.

my $object = My::Class->new( attr => [ 'foo', 'bar' ] );
say $object->my_count; ## ==> 2

delete( $index )

Arguments: Int.

Removes the indexed element from the array and returns it. Elements after it will be "moved up".

elements()

All elements in the array, in list context. (Essentially the same as all.)

my $object = My::Class->new( attr => [ 'foo', 'bar' ] );
my @list = $object->my_elements;
say Dumper( \@list ); ## ==> [ 'foo', 'bar' ]

first( $coderef )

Arguments: CodeRef.

Like List::Util::first().

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
my $found  = $object->my_first( sub { /a/ } );
say $found; ## ==> 'bar'

first_index( $coderef )

Arguments: CodeRef.

Like List::MoreUtils::first_index().

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
my $found  = $object->my_first_index( sub { /z$/ } );
say $found; ## ==> 2

flatten()

All elements in the array, in list context. (Essentially the same as all.)

my $object = My::Class->new( attr => [ 'foo', 'bar' ] );
my @list = $object->my_flatten;
say Dumper( \@list ); ## ==> [ 'foo', 'bar' ]

flatten_deep( $depth? )

Arguments: Optional[Int].

Flattens the arrayref into a list, including any nested arrayrefs. (Has the potential to loop infinitely.)

my $object = My::Class->new( attr => [ 'foo', [ 'bar', [ 'baz' ] ] ] );
say Dumper( [ $object->my_flatten_deep ] ); ## ==> [ 'foo', 'bar', 'baz' ]

my $object2 = My::Class->new( attr => [ 'foo', [ 'bar', [ 'baz' ] ] ] );
say Dumper( [ $object->my_flatten_deep(1) ] ); ## ==> [ 'foo', 'bar', [ 'baz' ] ]

for_each( $coderef )

Arguments: CodeRef.

Chainable method which executes the coderef on each element of the array. The coderef will be passed two values: the element and its index.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
$object->my_for_each( sub { say "Item $_[1] is $_[0]." } );

for_each_pair( $coderef )

Arguments: CodeRef.

Chainable method which executes the coderef on each pair of elements in the array. The coderef will be passed the two elements.

get( $index )

Arguments: Int.

Returns a single element from the array by index.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
say $object->my_get(  0 ); ## ==> 'foo'
say $object->my_get(  1 ); ## ==> 'bar'
say $object->my_get( -1 ); ## ==> 'baz'

grep( $coderef )

Arguments: CodeRef.

Like grep from perlfunc.

head( $count )

Arguments: Int.

Returns the first $count elements of the array in list context.

insert( $index, $value )

Arguments: Int, Any.

Inserts a value into the array with the given index. Elements after it will be "moved down".

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
$object->my_insert( 1, 'quux' );
say Dumper( $object->attr ); ## ==> [ 'foo', 'quux', 'bar', 'baz' ]

is_empty()

Boolean indicating if the referenced array is empty.

my $object = My::Class->new( attr => [ 'foo', 'bar' ] );
say $object->my_is_empty; ## ==> false
$object->_set_attr( [] );
say $object->my_is_empty; ## ==> true

join( $with? )

Arguments: Optional[Str].

Returns a string joining all the elements in the array; if $with is omitted, defaults to a comma.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
say $object->my_join;        ## ==> 'foo,bar,baz'
say $object->my_join( '|' ); ## ==> 'foo|bar|baz'

map( $coderef )

Arguments: CodeRef.

Like map from perlfunc.

max()

Like List::Util::max().

maxstr()

Like List::Util::maxstr().

min()

Like List::Util::min().

minstr()

Like List::Util::minstr().

natatime( $n, $callback? )

Arguments: Int, Optional[CodeRef].

Given just a number, returns an iterator which reads that many elements from the array at a time. If also given a callback, calls the callback repeatedly with those values.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
my $iter   = $object->my_natatime( 2 );
say Dumper( [ $iter->() ] ); ## ==> [ 'foo', 'bar' ]
say Dumper( [ $iter->() ] ); ## ==> [ 'baz' ]

not_all_true( $coderef )

Arguments: CodeRef.

Like List::Util::notall().

pairfirst( $coderef )

Arguments: CodeRef.

Like List::Util::pairfirst().

pairgrep( $coderef )

Arguments: CodeRef.

Like List::Util::pairgrep().

pairkeys()

Like List::Util::pairkeys().

pairmap( $coderef )

Arguments: CodeRef.

Like List::Util::pairmap().

pairs()

Like List::Util::pairs().

pairvalues()

Like List::Util::pairvalues().

pick_random( $count )

Arguments: Optional[Int].

If no $count is given, returns one element of the array at random. If $count is given, creates a new array with that many random elements from the original array (or fewer if the original array is not long enough) and returns that as an arrayref or list depending on context

pop()

Removes the last element from the array and returns it.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
say $object->my_pop; ## ==> 'baz'
say $object->my_pop; ## ==> 'bar'
say Dumper( $object->attr ); ## ==> [ 'foo' ]

print( $fh?, $with? )

Arguments: Optional[FileHandle], Optional[Str].

Prints a string joining all the elements in the array; if $fh is omitted, defaults to STDOUT; if $with is omitted, defaults to a comma.

product()

Like List::Util::product().

push( @values )

Adds elements to the end of the array.

my $object = My::Class->new( attr => [ 'foo' ] );
$object->my_push( 'bar', 'baz' );
say Dumper( $object->attr ); ## ==> [ 'foo', 'bar', 'baz' ]

reduce( $coderef )

Arguments: CodeRef.

Like List::Util::reduce().

reductions( $coderef )

Arguments: CodeRef.

Like List::Util::reductions().

reset()

Resets the attribute to its default value, or an empty arrayref if it has no default.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
$object->my_reset;
say Dumper( $object->attr ); ## ==> []

reverse()

Returns the reversed array in list context.

sample( $count )

Arguments: Int.

Like List::Util::sample().

set( $index, $value )

Arguments: Int, Any.

Sets the element with the given index to the supplied value.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
$object->my_set( 1, 'quux' );
say Dumper( $object->attr ); ## ==> [ 'foo', 'quux', 'baz' ]

shallow_clone()

Creates a new arrayref with the same elements as the original.

shift()

Removes an element from the start of the array and returns it.

my $object = My::Class->new( attr => [ 'foo', 'bar', 'baz' ] );
say $object->my_shift; ## ==> 'foo'
say $object->my_shift; ## ==> 'bar'
say Dumper( $object->attr ); ## ==> [ 'baz' ]

shuffle()

Returns the array in a random order; can be called in list context or scalar context and will return an arrayref in the latter case.

shuffle_in_place()

Rearranges the array in a random order, and changes the attribute to point to the new order.

sort( $coderef? )

Arguments: Optional[CodeRef].

Like sort from perlfunc.

sort_in_place( $coderef? )

Arguments: Optional[CodeRef].

Like sort from perlfunc, but changes the attribute to point to the newly sorted array.

splice( $index, $length, @values )

Like splice from perlfunc.

sum()

Like List::Util::sum0().

tail( $count )

Arguments: Int.

Returns the last $count elements of the array in list context.

uniq()

Returns the array filtered to remove duplicates; can be called in list context or scalar context and will return an arrayref in the latter case.

uniq_in_place()

Filters the array to remove duplicates, and changes the attribute to point to the filtered array.

uniqnum()

Returns the array filtered to remove duplicates numerically; can be called in list context or scalar context and will return an arrayref in the latter case.

uniqnum_in_place()

Filters the array to remove duplicates numerically, and changes the attribute to point to the filtered array.

uniqstr()

Returns the array filtered to remove duplicates stringwise; can be called in list context or scalar context and will return an arrayref in the latter case.

uniqstr_in_place()

Filters the array to remove duplicates stringwise, and changes the attribute to point to the filtered array.

unshift( @values )

Adds an element to the start of the array.

my $object = My::Class->new( attr => [ 'foo' ] );
$object->my_unshift( 'bar', 'baz' );
say Dumper( $object->attr ); ## ==> [ 'bar', 'baz', 'foo' ]

EXTENDED EXAMPLES

Using for_each

use strict;
use warnings;

package My::Plugin {
  use Moo::Role;
  sub initialize {}
  sub finalize {}
}

package My::Processor {
  use Moo;
  use Sub::HandlesVia;
  use Types::Standard qw( ArrayRef ConsumerOf );
  
  has plugins => (
    is => 'ro',
    isa => ArrayRef[ ConsumerOf['My::Plugin'] ],
    handles_via => 'Array',
    handles => {
      add_plugin => 'push',
      plugin_do => 'for_each',
    },
    default => sub { [] },
  );
  
  sub _do_stuff {
    return;
  }
  
  sub run_process {
    my ( $self, @args ) = @_;
    $self->plugin_do( sub {
      my $plugin = shift;
      $plugin->initialize( $self, @args );
    } );
    $self->_do_stuff( @args );
    $self->plugin_do( sub {
      my $plugin = shift;
      $plugin->finalize( $self, @args );
    } );
  }
}

my $p = My::Processor->new();

package My::Plugin::Noisy {
  use Moo; with 'My::Plugin';
  sub initialize {
    my ( $self, $processor, @args ) = @_;
    say "initialize @args"; ## ==> 'initialize 1 2 3'
  }
  sub finalize {
    my ( $self, $processor, @args ) = @_;
    say "finalize @args"; ## ==> 'finalize 1 2 3'
  }
}

$p->add_plugin( My::Plugin::Noisy->new );

$p->run_process( 1, 2, 3 );

Job queue using push and shift

use strict;
use warnings;
use Try::Tiny;

package My::JobQueue {
  use Moo;
  use Sub::HandlesVia;
  use Types::Standard qw( Bool ArrayRef CodeRef HasMethods is_Object );
  use Try::Tiny;
  
  has auto_requeue => (
    is => 'ro',
    isa => Bool,
    default => 0,
  );
  
  has jobs => (
    is => 'ro',
    isa => ArrayRef[ CodeRef | HasMethods['run'] ],
    handles_via => 'Array',
    handles => {
      add_job => 'push',
      _get_job => 'shift',
      is_empty => 'is_empty',
    },
    default => sub { [] },
  );
  
  sub _handle_failed_job {
    my ( $self, $job ) = @_;
    $self->add_job( $job ) if $self->auto_requeue;
  }
  
  sub run_jobs {
    my $self = shift;
    while ( not $self->is_empty ) {
      my $job = $self->_get_job;
      try {
        is_Object($job) ? $job->run() : $job->();
      }
      catch {
        $self->_handle_failed_job( $job );
      };
    }
  }
}

my $q = My::JobQueue->new();

my $str = '';
$q->add_job( sub { $str .= 'A' } );
$q->add_job( sub { $str .= 'B' } );
$q->add_job( sub { $str .= 'C' } );

$q->run_jobs;

say $str; ## ==> 'ABC'

# Attempt to push invalid value on the queue
#
try {
  $q->add_job( "jobs cannot be strings" );
}
catch {
  say $q->is_empty;  ## ==> true
};

BUGS

Please report any bugs to https://github.com/tobyink/p5-sub-handlesvia/issues.

SEE ALSO

Sub::HandlesVia.

AUTHOR

Toby Inkster <tobyink@cpan.org>.

COPYRIGHT AND LICENCE

This software is copyright (c) 2020, 2022 by Toby Inkster.

This is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.

DISCLAIMER OF WARRANTIES

THIS PACKAGE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.