diff --git a/modules/Bio/EnsEMBL/Utils/Scalar.pm b/modules/Bio/EnsEMBL/Utils/Scalar.pm index 3f0bd3d341ccdb2d346b991f77726cd6fa758d37..9ab0baf8f0fe77c00514176ffe2223a8b18e625f 100644 --- a/modules/Bio/EnsEMBL/Utils/Scalar.pm +++ b/modules/Bio/EnsEMBL/Utils/Scalar.pm @@ -106,11 +106,12 @@ our @EXPORT_OK; assert_ref assert_ref_can assert_numeric assert_integer assert_boolean assert_strand assert_file_handle wrap_array scope_guard + split_array ); %EXPORT_TAGS = ( 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)], - array => [qw/wrap_array/], + array => [qw/wrap_array split_array/], all => [@EXPORT_OK] ); @@ -416,6 +417,33 @@ sub assert_file_handle { 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 Arg [1] : CodeRef The block of code to exit once it escapes out of scope diff --git a/modules/t/utilsScalar.t b/modules/t/utilsScalar.t index 338338a31d83f10bc396f30af8207698c47c3ec8..95acb456838ef1615fd267f530f0edf7e0df0737 100644 --- a/modules/t/utilsScalar.t +++ b/modules/t/utilsScalar.t @@ -159,4 +159,14 @@ close($_) for ($scalar_fh, $other_scalar_fh); 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();