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

Re: Word wrapping using a regex.

by TJPride (Pilgrim)
on Dec 06, 2011 at 22:07 UTC ( #942125=note: print w/replies, xml ) Need Help??


in reply to Word wrapping using a regex.

Your regex is obviously not working properly, because it prints beyond the boundary of 50 characters. Here's another option:

use strict; use warnings; my $string = "I'm trying to have a word wrapping using a regex in Perl +. What I would like is about every 50 characters or so to check for +the next white-space occurrence and replace that space with a newline +, and then do this for the whole string. I'd like to avoid looping o +ne character at a time or using substr or placing the value into an a +rray if possible. The code sample I have works, I'd like someone opti +on and suggestion is there a better way or better regular expression +to accomplish this."; print '1234567890'x5 . "\n"; print wrap($string, 50) . "\n"; sub wrap { my ($s, $wrap) = @_; my (@lines, $line); while (length $s > $wrap) { ### Take one extra character so we can see if ### we're wrapping inside a word or not $line = substr($s, 0, $wrap+1); $line =~ s/\s+(\S*)$//; push @lines, $line; ### Add any word fragments back on $s = $1 . substr($s, $wrap); $s =~ s/^\s+//; } return join "\n", @lines; }

Replies are listed 'Best First'.
Re^2: Word wrapping using a regex.
by Additude (Initiate) on Nov 14, 2012 at 14:26 UTC
    I think to make this work we need to add another line at the end to tell it what to do with the last of the string that is less than $wrap.
    sub wrap { my ($s, $wrap) = @_; my (@lines, $line); while (length $s > $wrap) { ### Take one extra character so we can see if ### we're wrapping inside a word or not $line = substr($s, 0, $wrap+1); $line =~ s/\s+(\S*)$//; push @lines, $line; ### Add any word fragments back on $s = $1 . substr($s, $wrap); $s =~ s/^\s+//; } push @lines, $s; ## Adds the the last of the $s string to @lines return join "\n", @lines; }

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (5)
As of 2016-10-01 23:13 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    How many different varieties (color, size, etc) of socks do you have in your sock drawer?






    Results (9 votes). Check out past polls.