in reply to Re^2: substr question
in thread substr question
Ah... the original post said 'around 100 characters' not that that was the maximum. But no matter.
Sigh. I suppose I did commit the cardinal sin of posting Sloppy code.
And, I should have been clear that what I posted was NOT a turnkey solution but a suggestion that a regex approach might make sense.
so... OK, below is the result of another few minutes fiddling, this will work better, certainly.
my $string; $string = 'lasdufaner%.alsdfi,' x 100; # $string = 'freddy\'s wife wilma, ' x 100; my $max = 100; if ( $string and length $string > $max ){ $string = substr( $string, 0, $max); my ($tmp) = $string =~ /(.+)\s.*?$/; # last space if possible $tmp or ($tmp) = $string =~ /(.+)\W.*?$/; # bust on last non-word $tmp and $string = $tmp; print $string }
freddy's wife output:
freddy's wife wilma, freddy's wife wilma, freddy's wife wilma, freddy's wife wilma, freddy's wife
lasd... output
lasdufaner%.alsdfi,lasdufaner%.alsdfi,lasdufaner%.alsdfi,lasdufaner%.alsdfi,lasdufaner%.alsdfi
The point being, I suppose, that this sort of thing might be easily handled by a regular expression in most cases.
Thanks for your comment though, it's always good to have a second set of eyes. :-)
\s
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^4: substr question
by ikegami (Patriarch) on Jun 19, 2010 at 04:06 UTC | |
by stevenmay (Initiate) on Jun 19, 2010 at 05:24 UTC | |
by ikegami (Patriarch) on Jun 19, 2010 at 06:22 UTC | |
by stevenmay (Initiate) on Jun 19, 2010 at 16:25 UTC |