[tpm] Split a string in half

Madison Kelly linux at alteeve.com
Sat Mar 14 20:40:39 PDT 2009


Madison Kelly wrote:
> 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

For the record, I can do this now, but it's ugly as sin. Surely a TPM'er 
will have a more elegant/efficient method.

:)

My ugly way (where 'say_name' is the string in question):

-----------------------------------------
if (length($say_name)%2)
{
	my $half_count=(length($say_name)-1)/2;
	my $half_string="";
	my $i=0;
	foreach my $char (split//, $say_name)
	{
		$half_string.=$char;
		$i++;
		last if $i >= $half_count;
	}
	$say_name=$half_string if $say_name eq "$half_string $half_string";
}
-----------------------------------------

Madi


More information about the toronto-pm mailing list