Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Splitting a text file

by Ratazong (Prior)
on Mar 19, 2013 at 10:51 UTC ( #1024255=note: print w/ replies, xml ) Need Help??


in reply to Splitting a text file

Hi,

you are already on the right track. You might try to adapt your algorithm as follows (to keep most of your ideas/code)

  • open output-file #1
  • loop through the array (as in your code; for (my $x = 0; $x < $length; $x++))
    • write the current line ($array[$x])
    • check if you already wrote 1000 lines (use the modulo-operator, e.g. if ($x % 1000 == 999))
      • close the current file
      • open the next one
  • clean-up: close the last file
Hope that helps! Rata


Comment on Re: Splitting a text file
Select or Download Code
Replies are listed 'Best First'.
Re^2: Splitting a text file
by Dr Manhattan (Beadle) on Mar 20, 2013 at 05:05 UTC

    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?

      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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1024255]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others meditating upon the Monastery: (14)
As of 2015-07-31 11:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The top three priorities of my open tasks are (in descending order of likelihood to be worked on) ...









    Results (276 votes), past polls