假设file1看起来像这样:
bye bye hello thank you
而file2看起来像这样:
chao hola gracias
所需的输出是这样的:
bye bye chao hello hola thank you gracias
我自己已经提出了五种不同的方法来解决这个问题.但我认为必须有更多的方法,可能更简洁,更优雅的方式,我希望我能学到更多很酷的东西:)
以下是我迄今为止所尝试的内容,基于我从以前的问题的许多解决方案中学到的内容.此外,我正试图消化或内化我从Llama书中获得的知识.
代码1:
#!perl use autodie; use warnings; use strict; open my $file1,'<','c:/file1.txt'; open my $file2,'c:/file2.txt'; while(defined(my $line1 = <$file1>) and defined(my $line2 = <$file2>)){ die "Files are different sizes!\n" unless eof(file1) == eof(file2); $line1 .= $line2; $line1 =~ s/\n/ /; print "$line1 \n"; }
代码2:
#!perl use autodie; use warnings; use strict; open my $file1,'c:/file1.txt'; my @file1 = <$file1>; open my $file2,'c:/file2.txt'; my @file2 =<$file2>; for (my $n=0; $n<=$#file1; $n++) { $file1[$n] .=$file2[$n]; $file1[$n]=~s/\n/ /; print $file1[$n]; }
代码3:
#!perl use autodie; use warnings; use strict; open my $file1,'c:/file2.txt'; my %hash; while(defined(my $line1 = <$file1>) and defined(my $line2 = <$file2>)) { chomp $line1; chomp $line2; my ($key,$val) = ($line1,$line2); $hash{$key} = $val; } print map { "$_ $hash{$_}\n" } sort keys %hash;
代码4:
#!perl use autodie; use warnings; use strict; open my $file1,'c:/file2.txt'; while(defined(my $line1 = <$file1>) and defined(my $line2 = <$file2>)) { $line1 =~ s/(.+)/$1 $line2/; print $line1; }
代码5:
#!perl use autodie; use warnings; use strict; open my $file1,'c:/file1.txt'; my @file1 =<$file1>; open my $file2,'c:/file2.txt'; my @file2 =<$file2>; while ((@file1) && (@file2)){ my $m = shift (@file1); chomp($m); my $n = shift (@file2); chomp($n); $m .=" ".$n; print "$m \n"; }
我尝试过这样的事情:
foreach $file1 (@file2) && foreach $file2 (@file2) {...}
但是Perl给了我一个语法错误警告.我很沮丧.但我们可以同时运行两个foreach循环吗?