[tpm] Split a string in half

John Macdonald john at perlwolf.com
Tue Mar 24 07:36:42 PDT 2009

On Mon, Mar 23, 2009 at 01:58:17PM -0400, Madison Kelly wrote:
> Abuzar Chaudhary wrote:
>> my $s1 = substr($s, 0, int(length($s)/2));
>> my $s2 = substr($s, int(length($s)/2)+1);
> It doesn't get any cleaner than that!

Well... :-)

I'd get rid of the repeated computation of the length.  Either:

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


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

Especially for a human reader, code is clearer if the commonality
is shown explicitly, rather than having to inspect the expressions
to determine that they are the same - particularly when, as in this
case, they are only *almost the same* because of the +1.

More information about the toronto-pm mailing list