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

前端之家收集整理的这篇文章主要介绍了Perl遍历文件中的每一行并附加到另一个文件中每行的末尾前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有两个包含以下内容的文本文件

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相关文章