Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations MikeeOK on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to write into multiple files

Status
Not open for further replies.

rjuuser

Programmer
Dec 2, 2008
5
Hello,

I have a .csv file (converted from MS Excel) and my intention is to write every line into a separate (new) file. What I'm basically doing is this

Code:
#!/bin/perl

use warnings;
use strict;
use Text::CSV_XS;
use Tie::Handle::CSV;

my $fh = Tie::Handle::CSV->new(csv_parser => Text::CSV_XS->new({binary => 1}),
                               file       => 'myfile.csv',
                               header => 1);

my @data = <$fh>;
my $csv_line;

foreach $csv_line (@data) {
     print "Var1" . ": " . $csv_line->{'Variable1'} . "\n";
     print "Var2" . ": " . $csv_line->{'Variable1'} . "\n";
}

close $fh;

My question is how should I modify this code to be able to write every single line into a separate .csv file? The file names can be etc. from the first column of my data.
 
rjuuser said:
My question is how should I modify this code to be able to write every single line into a separate .csv file?
In the output from your example, it appears you're printing one column per line, I don't see where you're making a new CSV file.

Based on your example, try this:
Code:
use warnings;
use strict;
use Text::CSV_XS;
use Tie::Handle::CSV;

my $fh = Tie::Handle::CSV->new(file => 'myfile.csv',
                               header => 0);
my @headers = @{scalar <$fh>};

foreach my $csv_line (<$fh>) {
	open OUT, "> $csv_line->[0].txt" or die "Could not open file $csv_line->[0].txt for output.\n$!";
	for my $i (0..$#headers) {
		print OUT "$headers[$i]: $csv_line->[$i]\n";
	}
	close OUT;
}

close $fh;
 
Thanks! Your code works, I'll have to figure it out how it does this :)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top