Since people have shown how the use of a regex approach tends to be slower, here's a way to observe word boundaries (well, spaces between words, anyway) without using a regex:
my $maxlen = 20;
my $longtext = "This is some very long string that needs to be truncat
+ed to $maxlen characters...";
my $trunctext = substr( $longtext, 0, rindex( $longtext, " ", $maxlen
+));
print "$longtext\n$trunctext\n";
The rindex function, like substr, is faster than a regex match. | [reply] [d/l] |
By using duff's solution with the Matching the word boundary \b so that you don't chop off the text in the middle of a word.
update:
A clumsy other way to do this :)
use strict;
use warnings;
my $txt = "just wondering how i can have perl display part of my long
+memo. basically i want the first lets say 255 charachters of the para
+graph. im really new to perl so i don't know how i would come about t
+his? a regex perhaps? just started reading about that today. so basic
+ally something like";
my @a = split("",$txt);
my $l = 7;
for (my $i=0; $i < $l; $i++) {
print $a[$i];
$l++ if ($i ==($l-1) && ($a[$i] ne " " )) ;
}
"We all agree on the necessity of compromise. We just can't agree on when it's necessary to compromise." - Larry Wall.
| [reply] [d/l] |
actually the code given by graff works just fine:
my $max = 230;
(my $copy = $string) =~ s/(.{1,$max})\b.*/$1.../;
print "$copy\n";
Thanks! | [reply] [d/l] |