http://www.perlmonks.org?node_id=427195

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\