perl print statement
can anybody explain me this print statement in the following perl program.
#! /usr/bin/perl
use strict;
my %hash;
&Parse('first.txt');
&Parse('second.txt');
my $outputpath = 'output.txt';
unlink ($outputpath);
open (OUTPUT, ">>$outputpath") || die "Failed to open OUTPUT ($outputpath) - $!";
print OUT开发者_JAVA百科PUT "$_ \t" . join("\t", @{$hash{$_}}) . "\n" foreach (sort keys %hash);
close (OUTPUT) || die "Failed to close OUTPUT ($outputpath) - $!";
sub Parse {
my $inputpath = shift;
open (INPUT, "<$inputpath") || die "Failed to open INPUT ($inputpath) - $!";
while (<INPUT>) {
chomp;
my @row = split(/\t/, $_);
my $col1 = $row[0];
shift @row;
push(@{$hash{$col1}}, @row);
}
close (INPUT) || die "Failed to close INPUT ($inputpath) - $!";
return 1;
}
this is the statement:
print OUTPUT "$_ \t" . join("\t", @{$hash{$_}}) . "\n" foreach (sort keys %hash);
It's a foreach loop expressed via a postfix modifyer, which is equivalent to the following regular loop:
foreach (sort keys %hash) {
print OUTPUT "$_ \t" . join("\t", @{$hash{$_}}) . "\n";
}
Since there's no loop variable, the default $_
variable is used (in postfix loops, no named loop variable can be used, unlike regular ones). So, to make it more readable:
foreach my $key (sort keys %hash) {
print OUTPUT "$key \t" . join("\t", @{$hash{$key}}) . "\n";
}
@{$hash{$key}}
means take an array reference stored in $hash{$key} and make it into a real array, and join("\t", @{$hash{$key}})
takes that array and puts it in a tab-separated string.
So, for each of the keys in the hash (sorted in alphanumeric order), you would print the key name, followed by a space and a tab, followed by the contents of the arrayref (tab-separated) which is the has value for that key, followed by newline.
E.g. if the hash was ("c" => [1,2,3], "b => [11,12,13])
, it would print:
b [TAB]11[TAB]12[TAB]13
a [TAB]1[TAB]2[TAB]3
精彩评论