[tpm] Split a string in half

Alex Beamish talexb at gmail.com
Sun Mar 15 09:03:29 PDT 2009


This should do what you want ..

#!/usr/bin/perl -w
#
#  Split a string on the middle, assuming that the string is a repeated group
#  of words like 'foo bar foo bar', 'baz baz' or 'foo bar baz foo bar baz'.

use strict;

use Test::More tests => 3;

my %data = (
    'foo bar foo bar'         => [ 'foo bar',     'foo bar' ],
    'baz baz'                 => [ 'baz',         'baz' ],
    'foo bar baz foo bar baz' => [ 'foo bar baz', 'foo bar baz' ]
);

{
    foreach my $input ( keys %data ) {

        my $computedOutput = madiSplit($input);
        is_deeply( $computedOutput, $data{$input}, "Arrayrefs match" );
    }
}

sub madiSplit {
    my ($string) = @_;

    #  Break the entire string into individual words, and count the words.

    my @words = split( /\s+/, $string );
    my $words = scalar @words;

    #  Return an arrayref consisting of a string with the first n/2 words, then
    #  a string with the remaining n/s words.

    return (
        [
            join( ' ', @words[ 0 .. ( $words / 2 ) - 1 ] ),
            join( ' ', @words[ ( $words / 2 ) .. $words - 1 ] )
        ]
    );
}

-- 
Alex Beamish
Toronto, Ontario
aka talexb


More information about the toronto-pm mailing list