Perl - 以逗号分隔的输出,想要以CSV格式写入

时间:2014-04-18 21:43:46

标签: perl

以下是代码:

my @col= sort keys %colnames;

print "mRNA,".join(",",@col)."\n";
foreach my $row(keys %rownames){
    print "$row";
    foreach my $col(@col){
        my $num=$mat{$col}->{$row};
        $num=~s/(\.\d\d)\d+/$1/;
        print ",$num";
    }
    print "\n";
}

输出:

mRNA,Benzopyrene12h_replica1,Benzopyrene12h_replica2
E2F1,5.01,4.72
REV1,2.76,2.67
POLK,1.21,1.87
POLH,1.49,1.56
POLI,1.94,2.45

请帮助我将此输出写入.csv文件。

2 个答案:

答案 0 :(得分:1)

这样的事可能会奏效......结合米勒的回答。我没有测试它,只是给你一个想法。并且它可以写得更干净,更少冗余。

use strict;
use warnings;
use autodie;

my $csvFile = Text::CSV->new ( { binary => 1, eol => "\n" } )
                or die "Cannot use CSV: ".Text::CSV->error_diag ();

my @col= sort keys %colnames;
my @csv; 

$csv[0][0] = "mRNA,";
my @joinCol = join(",",@col);
my $i =1; 
foreach (@joinCol) {
    $csv[0][$i] = $_;
    $i++;
}    

my $k = 1; 
foreach my $row(keys %rownames){
    my $j = 0; 
    print "$row";
    $csv[$k][$j] = $row;
    foreach my $col(@col){
        my $num=$mat{$col}->{$row};
        $num=~s/(\.\d\d)\d+/$1/;        
        print ",$num";
        $csv[$k][$j] = $num; 
        $j++;
    }
    print "\n";
    $k++;
}

open $fh, '>', "new.csv" or die "Couldn't open csv file: $! \n";

for (@csv) {
    $csvFile->print($fh, $_);
}

close $fh;

答案 1 :(得分:0)

要写入CSV文件,请使用Text::CSV

use strict;
use warnings;
use autodie;

# Your Data Initialization
my %colnames; # = Something
my %rownames; # = Something else
my %mat; # = a hash of hash

# Prepare CSV
my $csv = Text::CSV->new ( { binary => 1, eol => "\n" } )
                or die "Cannot use CSV: ".Text::CSV->error_diag ();
open $fh, '>', "new.csv";

my @col = sort keys %colnames;

# Output Header
$csv->print($fh, ['mRNA', @col]);

# Output Rows
for my $row (keys %rownames){
    my @data = ($row);
    for my $col (@col){
        my $num = $mat{$col}{$row};
        $num =~ s/(\.\d\d)\d+/$1/;
        push @data, $num;
    }
    $csv->print($fh, \@data);
}

close $fh;