Beefy Boxes and Bandwidth Generously Provided by pair Networks
The stupid question is the question not asked

Re^2: Splitting a text file

by Dr Manhattan (Beadle)
on Mar 20, 2013 at 05:05 UTC ( #1024438=note: print w/replies, xml ) Need Help??

in reply to Re: Splitting a text file
in thread Splitting a text file

Hi all

I tried this and it seems to be working fine

my $length = $#array; my $fileNR = 1; for (my $x = 0; $x < $length; $x++) { open ($fileNR, ">$fileNR.txt") or die "can't open"; print $fileNR "$array[$x]\n"; if ($x % 1000 == 999) { close ($fileNR); $fileNR++; } }

Except that it doesn't print line 1 - 1000 to a file(as it should do), it just prints every 1000th line in a file, and then it goes on to the next file. Any idea why this happens?

Replies are listed 'Best First'.
Re^3: Splitting a text file
by Ratazong (Monsignor) on Mar 20, 2013 at 08:06 UTC

    Hi Dr Manhattan,

    have a look at the difference between my algorithm and your solution: you open the file in each iteration of the loop. And by opening a file for writing, you erase the previous content.

    The solution is to open the file before the loop. And (additionally) inside the if-block, when you want to switch to the next file.

    HTH, Rata

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1024438]
[Corion]: A good daystart everybody!
[Happy-the-monk]: Goody-goody!
[Discipulus]: still happy Happy-the-monk? even in 2018? good for you.. ;=)
[choroba]: Good morning!

How do I use this? | Other CB clients
Other Users?
Others making s'mores by the fire in the courtyard of the Monastery: (6)
As of 2018-01-23 08:42 GMT
Find Nodes?
    Voting Booth?
    How did you see in the new year?

    Results (242 votes). Check out past polls.