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

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

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

 



fixles
Novice

Oct 5, 2011, 10:51 AM

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

Hi,

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.


Code
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)]) {
$file_start->print($_);
}


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

Any help would be much appreciated.

Thanks,

James


Chris Charley
User

Oct 5, 2011, 6:21 PM

Post #2 of 3 (897 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 http://search.cpan.org/~mjd/Tie-File-0.96/lib/Tie/File.pm 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;
was:
print $new splice @array, 0, 100-1;

I was off by 1.


Code
  #!/usr/bin/perl   
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)


fixles
Novice

Oct 6, 2011, 1:50 AM

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

Hi,

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