Beefy Boxes and Bandwidth Generously Provided by pair Networks
Think about Loose Coupling
 
PerlMonks  

breaking up lines along white spaces with max length

by szabgab (Priest)
on Feb 02, 2005 at 10:13 UTC ( #427195=perlquestion: print w/ replies, xml ) Need Help??
szabgab has asked for the wisdom of the Perl Monks concerning the following question:

I have a string that I'd like to split up into chunks no longer than N characters.
I'd like to make sure I only split on white spaces. If no white space within the first N characters then I just split at N.

Comment on breaking up lines along white spaces with max length
Re: breaking up lines along white spaces with max length
by pelagic (Curate) on Feb 02, 2005 at 10:18 UTC
Re: breaking up lines along white spaces with max length
by Random_Walk (Parson) on Feb 02, 2005 at 10:36 UTC

    While pelagic's answer is probably the best way to go here is some script to do it too.

    #!/usr/bin/perl use warnings; use strict; my $length=10; while (<DATA>) { my @bits=split; # defaults to splitng $_ on whitespace foreach (@bits) { while ((length $_) > $length) { print "long one\n"; # here we substitute an empty string for the # first $length characters and printing the # ones replaced print ((substr $_, 0, $length, "")."\n"); } print "$_\n"; } } __DATA__ This one is fine ThisOneIsNotReallySoGood Here is a mixedbagoflongbits and then reasonably shortishbutnotshorten +ough

    Cheers,
    R.

    Pereant, qui ante nos nostra dixerunt!
      Carpe diem my dear!

      Update:
      I just realise "Pereant, qui ante nos nostra dixerunt" being your standard "disclaimer" ;)

      pelagic
Re: breaking up lines along white spaces with max length
by gellyfish (Monsignor) on Feb 02, 2005 at 11:14 UTC

    A crude way of doing this without a module would be:

    my $foo = '12345678901 23456789012345678901234567890123456789012345678 +901234567890123456789012345678901234567890'; + my $n = 15; + my @chunks = ($foo =~ /(\S{0,$n})\s?/g); + print join "\n",@chunks;

    /J\

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (6)
As of 2014-11-27 00:36 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My preferred Perl binaries come from:














    Results (178 votes), past polls