Reputation: 2356
Perl beginner here. I have built a hash oh hashes where the 'final' value is an array of strings. It looks like this:
my %sampleHash = ()
$sampleHash{$sample1} = {
R1Tests => \@sample1Results_1,
R2Tests => \@sample1Results_2,
};
$sampleHash{$sample2} = {
R1Tests => \@sample2Results_1,
R2Tests => \@sample2Results_2,
};
$sampleHash{$sample3} = {
R1Tests => \@sample3Results_1,
R2Tests => \@sample3Results_2,
};
I want to print the entire hash into a tab-delimited file that looks like this:
sample1 @sample1Results_1[0] @sample1Results_1[1] .... @sample1Results_2[0] @sample1Results_2[1] ...
sample2 @sample2Results_1[0] @sample2Results_1[1] .... @sample2Results_2[0] @sample2Results_2[1] ...
sample3 @sample3Results_1[0] @sample3Results_1[1] .... @sample3Results_2[0] @sample3Results_2[1] ...
What is an efficient way to do this? I know it involves a while or foreach loop, but I don't know how to make it print out to a file, do it column wise, and print out both sub-hashes on the same line.
Upvotes: 0
Views: 109
Reputation: 126762
I assume those arrays in your hash are really array references, and the semicolons are really commas?
It's very simple really. There are a few ways to do it, but I would use each
to iterate over the samples, and join
to assemble the contents.
Like this (untested, as I have only a tablet to hand while I'm travelling)
while (my ($sample, $results) = each %sampleHash) {
print join("\t",
$sample,
@{ $results->{R1Tests} },
@{ $results->{R2Tests} }
), "\n";
}
Upvotes: 3