[thelist] Perl string help
MILLER David R.
dmiller at mcc.ca
Tue Feb 13 13:51:54 CST 2007
Brilliant! However, I'd make the slight modification
$start += $split+1;
to drop the space itself.
Note that this presupposes that all spaces are single. You might want to
do
$text =~ s/ +/ /g;
or even
$text =~ s/\s+/ /g;
at the beginning to make sure that's true.
-----------------------------------------
David R. Miller
Senior Software Developer
Medical Council of Canada
-----------------------------------------
Original message:
Message: 20
Date: Tue, 13 Feb 2007 12:00:35 +0000
From: Struan Donald <struan at exo.org.uk>
Subject: Re: [thelist] Perl string help
To: thelist at lists.evolt.org
Message-ID: <20070213120035.GJ8971 at bollo.hoodee.co.uk>
Content-Type: text/plain; charset=us-ascii
* at 12/02 22:29 -0700 Amy Johnson said:
> Can anyone help me with a Perl string function? I need to take the
text
> from a textarea and split the string at the last blank space before
250
> characters. So if I have a 1000 character string, it would be cut
into
> about 4 or 5 strings at spaces between words.
>
> Any Perl gurus out there?
I am not a Perl guru but...
assuming $text contains the text you want to split up then the
following should work. At the end you'll have an array (@pieces)
which contains all the pieces.
my $piece_length = 250;
my @pieces;
my $start = 0;
while ( ( length($text) - $start ) > $piece_length ) {
my $split = rindex( substr( $text, $start, $piece_length ), ' ' );
push @pieces, substr($text, $start, $split);
$start += $split;
}
push @pieces, substr($text, $start);
cheers
Struan
More information about the thelist
mailing list