我有兩個嵌套的foreach循環。如果我用這個代碼:<DATA>防止執行foreach循環,爲什麼? :)
foreach (@directories) {
my $actual_directory = $_;
print "\nactual directory: ".$actual_directory."\n";
foreach (@files) {
my $file_name = $_;
my $actual_file = $actual_directory.$file_name;
print $actual_file."\n";
open(DATA, $actual_file) or die "Nelze otevřít zdrojový soubor: $!\n";
my $line_number = 0;
# while (<DATA>){
# my @znaky = split(' ',$_);
# my $poradi = $znaky[0]; #poradi nukleotidu
# my $hodnota = $znaky[1]; #hodnota
# my @temp = $files_to_sum_of_lines{$actual_file};
# $temp[$line_number] += $hodnota;
# $files_to_sum_of_lines{$actual_file} = @temp;
# $line_number+=1;
# }
# close(DATA);
}
}
我得到這樣的輸出:
actual directory: /home/n/Plocha/counting_files/1/
/home/n/Plocha/counting_files/1/a.txt
/home/n/Plocha/counting_files/1/b.txt
actual directory: /home/n/Plocha/counting_files/2/
/home/n/Plocha/counting_files/2/a.txt
/home/n/Plocha/counting_files/2/b.txt
但是,如果我去掉「while (<DATA>){ }
」,我失去A.TXT和b.txt,因此輸出看起來是這樣的:
actual directory: /home/n/Plocha/counting_files/1/
/home/n/Plocha/counting_files/1/a.txt
/home/n/Plocha/counting_files/1/b.txt
actual directory: /home/n/Plocha/counting_files/2/
/home/n/Plocha/counting_files/2/
/home/n/Plocha/counting_files/2/
這怎麼while (<DATA>)
阻止我的foreach被執行? 任何幫助將不勝感激。非常感謝。
看來,當$ _在while循環中被覆蓋時,它也正在更改文件數組。因爲直到$ _是undef,在目錄循環的下一次迭代中,@files僅包含undefs:D – vmpstr
@Sinan,typo - 我認爲你的意思是'while <$DATA>'引用你的詞法fh而不是內置DATA句柄。當命名一個文件句柄時,最好避免使用任何{DATA}命令:) – pilcrow
非常感謝,它的工作原理和確實更清晰的解決方案:) – Perlnika