CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
Search Posts SEARCH
Who's Online WHO'S
Log in LOG

Home: Perl Programming Help: Intermediate:
Move first n lines from one file to anther



Oct 5, 2011, 10:51 AM

Post #1 of 3 (1561 views)
Move first n lines from one file to anther Can't Post


I'm trying to process lines of a file 100 at a time and need to move the first 100 lines of one file into another. I cant populate the second file with 100 the first 100 lines but cant work out how to delete them from the original file. Here's what I have so far.

use strict; 
use warnings;
use IO::File;
use Slurp;

my $master_file = '.\db\MASTER_DATA.csv';
my $number_toscan = 100;

my @all_master_data = Slurp::to_array($master_file) or die;
my $file_start = IO::File->new('START.csv', 'w');

foreach (@all_master_data[0 .. ($number_toscan -1)]) {

I'm sure its pretty simple but I haven't found an answer on Google.

Any help would be much appreciated.



Chris Charley

Oct 5, 2011, 6:21 PM

Post #2 of 3 (1540 views)
Re: [fixles] Move first n lines from one file to anther [In reply to] Can't Post

I havent used either of the 2 modules you use but using Tie::File provides a way. There are other ways even without a module.

I haven't tried the code that follows and it will change your master file so you may want to back it up before you run this code :-)

Update: Changed the splice parameters to:
print $new splice @array, 0, 100;
print $new splice @array, 0, 100-1;

I was off by 1.

use strict;
use warnings;
use Tie::File;

my $master_file = '.\db\MASTER_DATA.csv';
my $new_file = 'START.csv';
#my $number_to_scan = 100;

tie my @array, 'Tie::File', $master_file or die "Unable to tie $master_file.\n$!";
open my $new, ">", $new_file or die "Unable to open $new_file for writing.\n$!";

print $new splice @array, 0, 100;

untie @array or die $!;
close $new or die $!;

I'm not sure that I can define a variable, (my @array), right there in the tie statement or if it needs to be defined before the tie statement.

(This post was edited by Chris Charley on Oct 6, 2011, 8:04 AM)


Oct 6, 2011, 1:50 AM

Post #3 of 3 (1520 views)
Re: [Chris Charley] Move first n lines from one file to anther [In reply to] Can't Post


Splice!!! I knew there had to be something like that to work on arrays. I had seen Tie before and considering just shift x number of times then looping a print statement with IO::File.

Your way is much better thanks!


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives