Ava Xue Ava Xue - 1 year ago 85
Perl Question

Perl: output array in a column

I was trying to grep string "Distance: " from "pairsAngles.txt" within each of over 2,000 subdirectories; the names of the subdirectories are obtained from a csv file.

However, the following code only give me a huge single line of output in csv format which I couldn't even open with an text editor:

my @pairs=qw();
my @result=();

my $in;
my $out;
my $pairs;
my $dist = "";
my $dir = "/home/avabelieve/aaPROJECT/helicalPair_ax/selectedPairs/renumberedPdb/clusterPairs-1.25-12-05_windows.12.resle3.2A.RMSD1.3/oligomerAngle";
my $cluster = "clst1.csv";
open ($in, $cluster) || die "cannot open \"$cluster\": $!";
my $cU = "clst1Updated.csv";
open ($out, ">$cU") || die "cannot open '$cU' $!";
my $csv = Text::CSV_XS->new ({ binary => 1, auto_diag => 1 });

while (my $c1 = <$in>) {
chomp $c1;
push @pairs, $c1;

foreach $c1 (uniq @pairs) {
find (\&Matches, "$dir/$c1");
sub Matches {
open ($pairs, "oligomerAngles.out") or die "$!";

while (my $dist = <$pairs>) {

if ($dist =~ m/Distance: /){

chomp $dist;
push (@result, "$dist\n");
@result = split ": ", $dist;

} } chdir "..";

if (not $csv->eof) {
$csv->print ($out, [uniq @pairs, @result]);
close $out or die "$!";

Answer Source

For some odd reason, Text::CSV_XS defaults to having no end-of-line separator when generating a CSV. From the docs for the eol attribute...

When [eol is] not passed in a generating instance, records are not terminated at all, so it is probably wise to pass something you expect. A safe choice for eol on output is either $/ or \r\n.

You can pass eol => $/ to Text::CSV_XS->new ($/ defaults to the newline appropriate for the current operating system) , or you can use $csv->say instead of $csv->print which uses $/ for its eol default. I'd recommend doing both.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download