Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

How do I wrap long lines at a fixed width, ignoring word boundaries?

by Haggis (Initiate)
on Jan 12, 2001 at 22:22 UTC ( [id://51419]=perlquestion: print w/replies, xml ) Need Help??

Haggis has asked for the wisdom of the Perl Monks concerning the following question: (data formatting)

I have a very long string containing no newlines. I want to insert a "\n" every 128 characters.

Text::Wrap doesn't do what I want as it breaks lines at whole words, resulting in lines that can be less than 128 characters.

Originally posted as a Categorized Question.

Replies are listed 'Best First'.
Re: How do I wrap long lines at a fixed width, ignoring word boundaries?
by davorg (Chancellor) on Jan 12, 2001 at 22:27 UTC
    sub fixedwidth_linebreaks { my( $str, $width ) = @_; my $newstr; while ( $str ) { $newstr .= substr( $str, 0, $width, '' )."\n"; } $newstr } $str = fixedwidth_linebreaks( $str, 128 );

    Note that this adds a newline onto the last segment, even if it's shorter than the specified width.

Re: How do I wrap long lines at a fixed width, ignoring word boundaries?
by chipmunk (Parson) on Jan 12, 2001 at 22:36 UTC

    You could do this with a substitution:

    s/(.{128})/$1\n/g;

    This does not add a newline to the final segment if it's shorter than 128 characters.

Re: How do I wrap a long string at 128 characters ignoring word boundaries?
by Anonymous Monk on Oct 15, 2004 at 23:05 UTC
    < P STYLE="word-wrap:break-word;width:100%;left:0"> LongWordLongWord.wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww..LongWordLongWord </P >

    Originally posted as a Categorized Answer.

Re: How do I wrap a long string at 128 characters ignoring word boundaries?
by Anonymous Monk on Oct 15, 2004 at 23:06 UTC
    < P STYLE="word-wrap:break-word;width:100%;left:0"> LongWordLongWord.wwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwwww..LongWordLongWord </P >

    Originally posted as a Categorized Answer.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2024-03-28 08:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found