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
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.