in reply to Split a string at a given line number

Untested:
my @chunks = $string =~ /(?|(?:((?:[^\n]*\n){19}[^\n]*)\n)|((?s:.*)))/ +g;
This does just as split, it loses every 20th newline. You can make it less complex is you want to keep the delimiter.

Replies are listed 'Best First'.
Re^2: Split a string at a given line number
by k_manimuthu (Monk) on May 12, 2010 at 12:29 UTC
    push @arr, $& while ($no=~ m/([^\n]+.*?\n){1,20}/gs); print "\n$_" for @arr;
      That works for me, but is there a way you can split it without the newlines being removed? Thanks.

        For my above code spliced the 20 lines and stored in a array format. Now that's changed to add a newline character in every 20th line and stored in a scalar variable.

        $new_string.="$&\n" while ($string=~ m/([^\n]+.*?\n){1,20}/gs); print "\n$new_string";
        With this, you could easily process whatever you want to process in the string.
Re^2: Split a string at a given line number
by danj35 (Sexton) on May 12, 2010 at 12:25 UTC

    Hi thanks for that. I've tested it and I can't seem to get that to work. At the moment my code for it looks like this:

    my @chunks = ($string =~ /(?|(?:((?:[^\n]*\n){19}[^\n]*)\n)|((?s:.*))) +/g); print Dumper @chunks[0];

    That returns the message:

    Sequence (?|...) not recognized in regex; marked by <-- HERE in m/(?| + <-- HERE (?:((?:[^\n]*\n){19}[^\n]*)\n)|((?s:.*)))/.

    Wouldn't know where to start with fixing that I'm afraid.

    Thanks.

      It seems you're running an old Perl. (?|) was introduced in the previous major version of Perl, 5.10, which was released 2.5 years ago.

      You may consider upgrading to 5.10, or even 5.12.

        Would be great, but I'm working on a company system here. Nothing can be upgraded without permissions and even with them 'free' software has a different definition for industry! Am trying to work with the one below, which works fine, but it removes the newlines from the string (which I might need to keep). Will keep battling with this!