perlnoobster has asked for the wisdom of the Perl Monks concerning the following question:

Hi gurus, I really hope someone can help me, i've got a text file containing 200 rows, i'd like for the 200 rows to be split into 4 outputs of 50, is this possible? if so how? I am a newbie to perl and this is my attempt in progress:
open (CQATEXTFILE, 'test.txt'); my $counter = 0; while (<FILE>) { if ( ++$counter % 5 == 0 ) { @results=split '\t',$results; push (@id,$results[0]); $_ = defined($_) ? $_ : '' for @results; # deal with empty fields $atom{$results[0]}=$results[1]; $category{$results[0]}=$results[2]; $title{$results[0]}=$results[3]; $counter++; } }

Replies are listed 'Best First'.
Re: Group every 50 rows
by cheekuperl (Monk) on Jul 18, 2012 at 14:39 UTC
    Can you derive a clue from the following?
    $lim=3; while(<DATA>) { if(0 == ($ctr % $lim) ) { print "\n\nNext group of $lim is...\n"; } print ; $ctr++; } __DATA__ one two three four five six seven eight nine ten
    This is just to "send" the clue. No boundary conditions tested :)
Re: Group every 50 rows
by aitap (Curate) on Jul 18, 2012 at 15:01 UTC
    You can use $. variable instead of incremeting $counter. See perlvar.
    Sorry if my advice was wrong.
Re: Group every 50 rows
by pvaldes (Chaplain) on Jul 18, 2012 at 14:46 UTC

    Very similar to a problem posted a few days ago.

    perl -ne 'print if $. <= 50' test.txt > first_50.txt perl -ne 'print if $. > 50 && $. <= 100' test.txt > 51_to_100.txt perl -ne 'print if $. > 100 && $. <= 150' test.txt > 101_to_150.txt perl -ne 'print if $. > 150 && $. <= 200' test.txt > mylittlepony.txt
Re: Group every 50 rows
by BillKSmith (Monsignor) on Jul 18, 2012 at 17:31 UTC

    You did not tell us if you want the first 50 rows or every fourth row in the first output.

Re: Group every 50 rows
by locked_user sundialsvc4 (Abbot) on Jul 18, 2012 at 15:31 UTC

    Set up a counter equal to zero (say...) outside the loop, then increment it each time.   After incrementing it (so that the initial value is 1...), test to see if “counter modulo 50” is equal to zero.   As all of the above examples do.   If so, print a newline or two.

    Modulo, of course, is the remainder obtained from a division operation.   When zero, you know that the counter is now some multiple of (say) 50.