【发布时间】:2013-01-21 16:15:55
【问题描述】:
我有两个包含以下内容的文本文件:
FILE1.txt
dog
cat
antelope
FILE2.txt
1
2
Barry
我想要实现的输出如下:
dog1
dog2
dogBarry
cat1
cat2
catBarry
antelope1
antelope2
antelopeBarry
他们按照我的方式去做:
open (FILE1, "<File1.txt") || die $!;
open (FILE2, "<File2.txt") || die $!;
my @animals = (<FILE1>); #each line of the file into an array
my @otherStrings = (<FILE2>); #each line of the file into an array
close FILE1 || die $!;
close FILE2 || die $!;
my @bothTogether;
foreach my $animal (@animals) {
chomp $animal;
foreach my $otherString (@otherStrings) {
chomp $otherString;
push (@bothTogether, "$animal$otherString");
}
}
print @bothTogether;
我的做法很有效,但我确信这不是最好的方法尤其是当文件都可能包含数千行时?
最好的方法是什么,也许使用哈希?
【问题讨论】:
-
如果文件太大而无法存储,您只能在处理时读取它们(而不是之前,就像现在一样)。哈希无济于事,因为无论如何您都会将所有内容加载到内存中;并且您无论如何都在处理“foreach”。
-
记一下,你也可以:
my @animals = chomp(<FILE1>); -
另外我认为你的脚本在记忆方面是可以的,因为只有生成的文件会很大 - 你逐行编写它。