per*_*ser 4 perl hash text file
我有两个包含以下内容的文本文件:
FILE1.TXT
dog
cat
antelope
Run Code Online (Sandbox Code Playgroud)
FILE2.TXT
1
2
Barry
Run Code Online (Sandbox Code Playgroud)
我想要实现的输出如下:
dog1
dog2
dogBarry
cat1
cat2
catBarry
antelope1
antelope2
antelopeBarry
Run Code Online (Sandbox Code Playgroud)
他们这样做了我:
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;
Run Code Online (Sandbox Code Playgroud)
我这样做的方式有效,但我确定它不是最好的方式,特别是当文件都包含数千行时?
这样做的最佳方式是什么,可能使用哈希?
小智 5
您的方法适用于包含数千行的文件.那真的不是那么大.对于数百万行,这可能是一个问题.
但是,你可以通过阅读只有一个文件到内存中,并没有立即打印它们存储在一个数组的结果减少代码的内存使用情况:
use warnings;
use strict;
open my $animals, '<', 'File1.txt' or die "Can't open animals: $!";
open my $payloads, '<', 'File2.txt' or die "Can't open payloads: $!";
my @payloads = <$payloads>; #each line of the file into an array
close $payloads or die "Can't close payloads: $!";
while (my $line = <$animals>) {
chomp $line;
print $line.$_ foreach (@payloads);
}
close $animals or die "Can't close animals: $!";
Run Code Online (Sandbox Code Playgroud)
有两个相同大小的大文件,这将占用原始代码大约1/4的内存.
更新:我还编辑了代码,包括Simbabque对其进行现代化的好建议.
更新2:正如其他人已经注意到的那样,您既不能将文件读入内存,又会在动物文件的每一行上逐行检查有效负载文件.但是,这会慢得多.除非绝对必要,否则应该避免.我建议的方法与原始代码的速度大致相同.
| 归档时间: |
|
| 查看次数: |
12119 次 |
| 最近记录: |