I think the method is a bit cumbersome. And you could get ugly multiple "..."s - at least, the way you have written the algorithm. Rather than continually shortening the string, why not just:

1. Check if it is too long
2. If not, print it
3. If so, get the last word and as many words from the start as you can, then put a "..." in. If the last word is more than 12 chars, just get as many words from the start as you can; if the first word is more than 12 chars, truncate it.

Short and simple. Although I think sometimes people obsess about speed... if it's building a webpage, this is not an algorithm that is gonna be run a million times. But simple code is easy to debug.

if (length ($string) > 15) { my $last; if ($string =~ /\s(\S{1,12})$/) { $last = $1; # a suitable end word } $starting_length = 12 - length($last); if ($string =~ /(.{0,$starting_length})\s/) { # greedy pattern match +, matches multiple words $string = "$1...$last"; } else { $string = substr($string,0,12) . "..."; } }

You could prolly do that last if.. else just with s/// and checking if the match was successful:

( $string =~ s/(.{0,$starting_length})\s/"$1...$last"/e ) or $string = + substr($string,0,12) . "...";

Actually, you really want to check the first word length first. You probably want words from the start rather than the end (more recognisable), but this grabs as much as it can from the end, then cuts the start to suit. Well, play with it. dave hj~


In reply to Re: Smart Substrings by dash2
in thread Smart Substrings by cei

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.