[tpm] Split a string in half

Indy Singh indy at indigostar.com
Tue Mar 24 08:12:02 PDT 2009


Here is a way to do it with a regular expression:
my $l = int (length($s)/2);
my ($a, $b) = $s =~ qr/(.{$l}) (.*$)/;


Or with more explicit documentation:
my $l = int (length($s)/2);
my $split_in_half = qr/(.{$l}) (.*$)/;
my ($a, $b) = $s =~ /$split_in_half/;


Note: The assignment to ($a, $b) is in array context, the two variables 
must be enclosed in brackets.


Indy Singh
IndigoSTAR Software -- www.indigostar.com


----- Original Message ----- 
From: "Madison Kelly" <linux at alteeve.com>
To: "Toronto Perl Mongers" <tpm at to.pm.org>
Sent: Saturday, March 14, 2009 11:21 PM
Subject: [tpm] Split a string in half


> Hi all,
>
>   I need to split a sting in half, and I can assume the the middle 
> character in the string will be a space ' ' character. I cannot 
> predict how many spaces will be in the string though.
>
>   In short; How could I split:
>
> 'foo bar foo bar' => 'foo bar', 'foo bar'
> 'baz baz'         => 'baz', baz'
> 'foo bar baz foo bar baz' => 'foo bar baz', 'foo bar baz'
>
>   In Detail;
>
>   I use WWW::Mechanize, and I am running into a problem with a website 
> that uses an image and text in a single anchor. Specifically, the alt 
> text is the same as the text, so the 'find_all_links' function 
> returns:
>
> foo bar foo bar
>
>   For:
>
> <a href="..."><img src="..." alt="foo bar"> foo bar</a>
>
>   I never know what the link will be, only that the alt and text will 
> be that same.
>
> Thanks!
>
> Madi
> _______________________________________________
> toronto-pm mailing list
> toronto-pm at pm.org
> http://mail.pm.org/mailman/listinfo/toronto-pm 



More information about the toronto-pm mailing list