Beefy Boxes and Bandwidth Generously Provided by pair Networks
Clear questions and runnable code
get the best and fastest answer
 
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?
[choroba]: just one of its angles, in fact
[LanX]: <|--
[choroba]: Reminds me of an old joke about an orchestra...
erix imagines that in a true Lancs accent
[choroba]: so a Czech orchestra rehearses a new piece by a German composer
LanX LOL of the day ... the Turkish Anonymous Alcoholics stopped their "No to alcohol" campaign for political reasons ...
LanX omg my browser is posting again on its own ...
[LanX]: choroba: GREAT JOKE! xD

How do I use this? | Other CB clients
Other Users?
Others chanting in the Monastery: (5)
As of 2017-03-27 11:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (319 votes). Check out past polls.