Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses

Split a string at a given line number

by danj35 (Sexton)
on May 12, 2010 at 10:28 UTC ( #839596=perlquestion: print w/replies, xml ) Need Help??
danj35 has asked for the wisdom of the Perl Monks concerning the following question:

Hey monks,

Asked an question earlier about counting the number of lines in a string (not a file)( The code works fine for this:

my $count = ($string =~ tr/\n//);

Now I need to split the $string at line 20. Anyone know how to do this?


Replies are listed 'Best First'.
Re: Split a string at a given line number
by Corion (Pope) on May 12, 2010 at 10:29 UTC

    How about splitting the string at every line and then joining the first 20 together again, and the rest as well?

Re: Split a string at a given line number
by JavaFan (Canon) on May 12, 2010 at 10:46 UTC
    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.
      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.

      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.


        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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://839596]
Approved by Hue-Bond
and the voices are still...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (10)
As of 2018-05-23 13:12 GMT
Find Nodes?
    Voting Booth?