Beefy Boxes and Bandwidth Generously Provided by pair Networks
Keep It Simple, Stupid
 
PerlMonks  

breaking up lines along white spaces with max length

by szabgab (Priest)
on Feb 02, 2005 at 10:13 UTC ( [id://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

Replies are listed 'Best First'.
Re: breaking up lines along white spaces with max length
by pelagic (Priest) on Feb 02, 2005 at 10:18 UTC
Re: breaking up lines along white spaces with max length
by Random_Walk (Prior) 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
Domain Nodelet?
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?Last hourOther CB clients
Other Users?
Others admiring the Monastery: (7)
As of 2024-04-24 09:50 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found