Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW

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
[Corion]: marto: You wrote Perl? Or did you have to work (and wrote Perl)?
[marto]: the fun part, I had no fun this weekend, very stressful :)
[Corion]: But I feel an introductory talk gestating, working title "Reading CPAN" - how to read module documentation, how to judge a module, how to read the module tests/examples
[Corion]: marto: Ouch :-/ The kids are making trouble?
[Corion]: Meh - food becons, and colleagues are staring at me, talk to you later, sorry!

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (6)
As of 2017-08-21 09:35 GMT
Find Nodes?
    Voting Booth?
    Who is your favorite scientist and why?

    Results (319 votes). Check out past polls.