简体   繁体   English

perl打印声明

[英]perl print statement

can anybody explain me this print statement in the following perl program. 谁能在以下perl程序中向我解释此打印声明。

#! /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 OUTPUT "$_ \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循环,它等效于以下常规循环:

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. @{$hash{$key}}表示将存储在$ hash {$ key}中的数组引用转换为真实数组,而join("\\t", @{$hash{$key}})采用数组,并将其放在制表符分隔的字符串中。

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. 因此,对于哈希中的每个键(按字母数字顺序排序),您将打印键名称,后跟一个空格和一个制表符,然后是arrayref的内容(制表符分隔),该值是那个键,然后是换行符。

Eg if the hash was ("c" => [1,2,3], "b => [11,12,13]) , it would print: 例如,如果哈希为("c" => [1,2,3], "b => [11,12,13]) ,它将显示:

b [TAB]11[TAB]12[TAB]13
a [TAB]1[TAB]2[TAB]3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM