Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

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

by davido (Archbishop)
on Jul 19, 2004 at 08:26 UTC ( #375488=note: print w/ replies, xml ) Need Help??


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

This snippet uses a pure regexp approach to breaking a string up into stringlets of no more than 'n' length, broken on the first whitespace before 'n', OR a hard break at 'n' characters if there is no preceeding whitespace on which to break. Not sure if this is what you're after, but it seems to be a start in the right direction. If you simply want to crop at 'n' or less (depending on whitespace), remove the /g modifier and capture only the first stringlet.

use strict; use warnings; while ( my $string = <DATA> ) { chomp $string; my ( @stringlets ) = $string =~ m/(?:.{0,40}(?:\s|$))|(?:\S{40})/gs; print "$_\n" foreach @stringlets; print "\n\n"; } __DATA__ Now is the time for all good men to come to the aid of their country. Nowisthetimeforallgoodmentocometotheaidoftheircountry.

Applying the "..." elipses is trivial at this point.

I hope this helps... it's late, I may have misread the question. ;)


Dave


Comment on Re: In search of a better way to trim string length
Download Code
Re^2: In search of a better way to trim string length
by kiat (Vicar) on Jul 19, 2004 at 09:00 UTC
    Thanks, Dave!

    I ran your code as is, but it doesn't quite give me the reuslts I was expecting. Maybe I'm missing something?

      Maybe I'm missing something?

      Only that I was just providing a starting point to illustrate a method. I figured you would tweak it to meet your needs. But in fairness, I should have provided an answer that produced exactly what you were looking for. I've modified my answer to do what I think your question was asking, and will paste it below...

      The problem with my original (I think) was that it broke your original string into substrings of 'n' characters. What you were looking for was simply truncation, with trailing '...' elipses. Here ya go...

      use strict; use warnings; my $len = 40; print "0123456789012345678901234567890123456789\n"; while ( my $string = <DATA> ) { chomp $string; $string =~ s/((?:.{0,$len}(?=\s|$))|(?:\S{$len}))(?:.+$)?/$1.../s; print "$string\n"; } __DATA__ Now is the time for all good men to come to the aid of their country. Nowisthetimeforallgoodmentocometotheaidoftheircountry.

      Hope this helps.


      Dave

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others wandering the Monastery: (12)
As of 2014-08-20 09:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (110 votes), past polls