Commit c6eb06d6 authored by Andy Yates's avatar Andy Yates
Browse files

Adding an array splitter

parent 6356b422
...@@ -106,11 +106,12 @@ our @EXPORT_OK; ...@@ -106,11 +106,12 @@ our @EXPORT_OK;
assert_ref assert_ref_can assert_numeric assert_integer assert_boolean assert_strand assert_file_handle assert_ref assert_ref_can assert_numeric assert_integer assert_boolean assert_strand assert_file_handle
wrap_array wrap_array
scope_guard scope_guard
split_array
); );
%EXPORT_TAGS = ( %EXPORT_TAGS = (
assert => [qw(assert_ref assert_ref_can assert_integer assert_numeric assert_boolean assert_strand assert_file_handle)], assert => [qw(assert_ref assert_ref_can assert_integer assert_numeric assert_boolean assert_strand assert_file_handle)],
check => [qw(check_ref check_ref_can)], check => [qw(check_ref check_ref_can)],
array => [qw/wrap_array/], array => [qw/wrap_array split_array/],
all => [@EXPORT_OK] all => [@EXPORT_OK]
); );
...@@ -416,6 +417,33 @@ sub assert_file_handle { ...@@ -416,6 +417,33 @@ sub assert_file_handle {
return 1; return 1;
} }
=head2 split_array
Arg [1] : Integer Maximum size of an array produced
Arg [2] : ArrayRef The array to split
Description : Takes an array of values and splits the array into multiple
arrays where the maximum size of each array is as specified
Example :
Returntype : ArrayRef of ArrayRefs where each element is a split list
=cut
sub split_array {
my ($amount, $array) = @_;
assert_ref($array, 'ARRAY', 'array');
my @split;
my $counter = 0;
my $index = 0;
foreach my $e (@$array) {
if($counter == $amount) {
$index++;
$counter = 0;
}
push(@{$split[$index]}, $e);
$counter++;
}
return \@split;
}
=head2 scope_guard =head2 scope_guard
Arg [1] : CodeRef The block of code to exit once it escapes out of scope Arg [1] : CodeRef The block of code to exit once it escapes out of scope
......
...@@ -159,4 +159,14 @@ close($_) for ($scalar_fh, $other_scalar_fh); ...@@ -159,4 +159,14 @@ close($_) for ($scalar_fh, $other_scalar_fh);
is($v, 'wibble', 'Value has been reset even after a die'); is($v, 'wibble', 'Value has been reset even after a die');
} }
#Array split
{
my $original_array = [1..7];
my $split_two = split_array(2, $original_array);
is_deeply($split_two, [[1,2],[3,4],[5,6],[7]], 'Checking split of 7 element array into arrays of max size 2') or diag explain $split_two;
my $split_ten = split_array(10, $original_array);
is_deeply($split_ten, [$original_array], 'Checking split of 7 element array into arrays of max size 10') or diag explain $split_ten;
dies_ok { split_array(1, {}) } 'Passing in a non-array ref means death';
}
done_testing(); done_testing();
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment