Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:
Hi Monks!
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 new line, and then do this for the whole string. I'd like to avoid looping one character at a time or using substr or placing the value into an array if possible. The code sample I have works, I'd like one's option and suggestion if there is a better way or a better regular expression to accomplish this.
Here is the code:
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 new line, and then do this for the whole string. I'd like to avoid looping one character at a time or using substr or placing the value into an array if possible. The code sample I have works, I'd like one's option and suggestion if there is a better way or a better regular expression to accomplish this.
Here is the code:
Thanks for looking!#!/usr/bin/perl -w use strict; 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 sp +ace with a newline, and then do this for the whole string. I'd like to avoid looping one character at a time or using substr or p +lacing the value into an array if possible. The code sample I have works, I'd like someone option and suggestion i +s there a better way or better regular expression to accomplish this. +'; $string =~ s/(.{1,50}\S|\S+)\s+/$1\n/mg; print "$string\n"; exit;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Word wrapping using a regex.
by MidLifeXis (Monsignor) on Dec 06, 2011 at 16:53 UTC | |
by Anonymous Monk on Dec 06, 2011 at 18:09 UTC | |
by toolic (Bishop) on Dec 06, 2011 at 20:02 UTC | |
by Anonymous Monk on Dec 06, 2011 at 19:53 UTC | |
Re: Word wrapping using a regex.
by TJPride (Pilgrim) on Dec 06, 2011 at 22:07 UTC | |
by Additude (Initiate) on Nov 14, 2012 at 14:26 UTC |
Back to
Seekers of Perl Wisdom