Sub::Sequence - simplest, looping over an array in chunks
use Sub::Sequence; my @user_id_list = (1..10_000_000); seq \@user_id_list, 50, sub { my $list = shift; my $in_id = join ',', map { int $_; } @{$list}; # UPDATE table SET status=1 WHERE id IN ($id_cond) sleep 1; };
Sub::Sequence provides the function named 'seq'. You can treat an array with simple interface.
This function calls \&code with split array. And \&code takes $n items at a time(also give $step_count and $offset).
\&code
use Sub::Sequence; use Data::Dumper; my $result = seq [1, 2, 3, 4, 5], 2, sub { my ($list, $step, $offset) = @_; # ... Do something ... return $offset; }; warn Dumper($result); # [ 0, 2, 4 ]
NOTE: Return value of seq is the array reference of return values of \&code in scalar context. However, seq was called in the list context, then return value is the flatten list.
seq
use Sub::Sequence; use Data::Dumper; # scalar context my $foo = seq [1, 2, 3, 4, 5], 2, sub { my @list = @{ $_[0] }; return \@list; }; warn Dumper($foo); # [ [1, 2], [3, 4], [5] ] # list context my @bar = seq [1, 2, 3, 4, 5], 2, sub { my @list = @{ $_[0] }; return \@list; }; warn Dumper(\@bar); # [ 1, 2, 3, 4, 5 ]
Sub::Sequence is hosted on github <http://github.com/bayashi/Sub-Sequence>
Dai Okabayashi <bayashi@cpan.org>
An interface of this module was inspired by Sub::Retry.
Also check similar modules, Iterator::GroupedRange and natatime method in List::MoreUtils.
natatime
Lastly, see benchmark.pl (Sub::Sequence vs splice vs natatime) in samples directory.
benchmark.pl
samples
This module is free software; you can redistribute it and/or modify it under the same terms as Perl itself. See perlartistic.
To install Sub::Sequence, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sub::Sequence
CPAN shell
perl -MCPAN -e shell install Sub::Sequence
For more information on module installation, please visit the detailed CPAN module installation guide.