Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot
 
PerlMonks  

Re: How do I truncate a string while preserving words?

by Tomte (Priest)
on May 11, 2007 at 08:03 UTC ( #614841=note: print w/ replies, xml ) Need Help??


in reply to How do I truncate a string while preserving words?

Try

$string =~ s/^(.{0,$maxlength})\b.*$/$1.../s;
that should work as expected (at least as far as the presented code goes...).

Edit: explanation: you can ommit the upper bound, but not the lower bound, as you did. From perlre:

{n}? Match exactly n times {n,}? Match at least n times {n,m}? Match at least n but not more than m times
and you have to match the rest of the input (.*$) for it to be replaced too - otherwise you would simply insert the ellipsis (...) without truncating the input.

regards,
tomte


An intellectual is someone whose mind watches itself.
-- Albert Camus


Comment on Re: How do I truncate a string while preserving words?
Select or Download Code
Replies are listed 'Best First'.
Re^2: How do I truncate a string while preserving words?
by Cap'n Steve (Friar) on May 11, 2007 at 08:22 UTC
    Darn it, I swear I remember being able to omit the minimum number of matches. I wonder what it was doing with my regular expression since it didn't issue a warning. Thanks for pointing out the other error, too, I hadn't even thought about that yet.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://614841]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (6)
As of 2015-07-29 01:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (260 votes), past polls