Sunday, July 1, 2012

Split an Array into Two Equal Parts

This is a small snippet of Perl code which demonstrates a quick and easy way to take an array that contains an even number of elements and split it up into two smaller arrays.  Assuming the array values are read left to right, the array called @Left will store the first half of the array elements, while the array called @Right will store the second half of the array elements.  

use strict;
use warnings;

#generate 10 random numbers between 0 and 9
my $range=10;
my @nums = map { int(rand($range)) } ( 1..10 );

#splits array in half
my @Left = @nums;
my @Right = splice @Left, scalar(@nums)/2;

#formats data to visually show split
my $Lefthalf=join('',@Left);
my $Righthalf=join('',@Right);
print "$Lefthalf\n";
print "$Righthalf\n";

No comments: