gpt4 book ai didi

Perl 迭代文件中的每一行并附加到另一个文件中每一行的末尾

转载 作者:行者123 更新时间:2023-12-02 14:37:19 25 4
gpt4 key购买 nike

我有两个文本文件,其中包含以下内容:

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;

我的方法是有效的,但我确信这不是最好的方法特别是当文件都可能包含数千行时?

最好的方法是什么,也许使用哈希?

最佳答案

您的方法对于具有数千行的文件来说效果很好。那确实没那么大。对于数百万行来说,这可能是一个问题。

但是,您可以通过仅将一个文件读入内存并立即打印结果而不是将其存储在数组中来减少代码的内存使用量:

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: $!";

对于两个大小相等的大文件,这将使用大约原始代码的 1/4 内存。

更新:我还编辑了代码,以包含 Simbabque 对其现代化提出的良好建议。

更新 2: 正如其他人所指出的,您无法将这两个文件读入内存,而是在动物文件的每一行上逐行浏览有效负载文件。然而,这会慢得多。除非绝对必要,否则应避免这样做。我建议的方法与您的原始代码的速度大致相同。

关于Perl 迭代文件中的每一行并附加到另一个文件中每一行的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14729519/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com