[tpm] Split a string in half

Mike Stok mike at stok.ca
Sun Mar 15 10:08:18 PDT 2009


On Mar 15, 2009, at 12:03 PM, Alex Beamish wrote:

> 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 ] )
>        ]
>    );
> }


If the string is as Madi described and we're looking for  
'<stuff><space><stuff>' then wouldn't this be a plug-in replacement  
for the madiSplit subroutine above:

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

    return [$1, $1] if $string =~ /^(.*) \1$/;
    return;
}

If there was only one place in Madi's code where it was used then it  
might not even be worth turning into a subroutine as

   # check for duplicated alt & text
   $say_name = $1 if $say_name =~ /^(.*) \1$/;

might be sufficiently short & clear.  (Maybe the * could be a +  
depending on what you want to do with ' ')

Mike

-- 

Mike Stok <mike at stok.ca>
http://www.stok.ca/~mike/

The "`Stok' disclaimers" apply.






More information about the toronto-pm mailing list