Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

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)(http://www.perlmonks.org/?node_id=839575). 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?

Cheers

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
    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.
      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.

      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.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://839596]
Approved by Hue-Bond
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2016-07-28 06:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    What is your favorite alternate name for a (specific) keyboard key?


















    Results (253 votes). Check out past polls.