Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
PerlMonks  

Re: In search of a better way to trim string length

by theAcolyte (Pilgrim)
on Jul 19, 2004 at 08:09 UTC ( #375482=note: print w/replies, xml ) Need Help??


in reply to In search of a better way to trim string

sub trim_length { my($string, $desired_length) = @_; # edit: swiped idea from Tachyon if((length($string)) < $desired_length) { return $string; } my @words = split(" ", $string); my $clipped = ""; foreach(@words) { my $temp = $clipped; $clipped .= $_; if((length($clipped)) > $desired_length) { $clipped = $temp; last +; } } if((length($clipped)) == 0) { $clipped = substr($string, 0, $desired_length); } $clipped .= "..."; return $clipped }

Does the same as your code but with a little less effort. Breaks the string down into words, keeps adding words until it passes your minimum marker, then keeps the previous version. If the first word puts it over the minimum marker, then it goes back to the original $string and clips that.

theAcolyte

Replies are listed 'Best First'.
Re^2: In search of a better way to trim string length
by kiat (Vicar) on Jul 19, 2004 at 08:47 UTC
    Thanks, theAcolyte!

    Ran your code. I think you need to add a space here:

    $clipped .= $_; # orginal $clipped .= "$_ "; # changed
    With your code, when I passed the sub a string such as "this is a very long sentence without spaces in between", it gets transformed to "thisisaverylongsentencewithout" i.e. the original spaces were gone.

    cheers

      blah ... right you are! See what I get for posting untested code? Then again, I always post untested code ... :P

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://375482]
help
Chatterbox?
[ambrus]: choroba: heh heh... I have such a doc bug report somewhere. fixed by now.
[Corion]: Once upon a time I had automatic tests for checking the synopsis, but I stopped doing that because the setup was too fragile on CPAN testers for extracting code from the SYNOPSIS.
[Corion]: Maybe I should move the extraction of the code from the SYNOPSIS section into the author tests, or something like that...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (8)
As of 2017-02-27 12:08 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?






    Results (383 votes). Check out past polls.