[tpm] Split a string in half

Abuzar Chaudhary abuzarchaudhary at yahoo.com
Sun Mar 15 01:32:24 PDT 2009


my $s1 = substr($s, 0, int(length($s)/2));
my $s2 = substr($s, int(length($s)/2)+1);

--- On Sat, 3/14/09, Madison Kelly <linux at alteeve.com> wrote:

> From: Madison Kelly <linux at alteeve.com>
> Subject: Re: [tpm] Split a string in half
> To: "Toronto Perl Mongers" <tpm at to.pm.org>
> Date: Saturday, March 14, 2009, 11:40 PM
> 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
> _______________________________________________
> 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