perl 脚本按照另一个文件中列出的相同顺序对文件进行排序?

perl script to sort a file in the same order as listed in another file?

我想按照另一个 file.For 示例中遵循的特定顺序对文件内容进行排序,

输入文件 1:

dff_0_1:G11

dff_0_5:N_25

dff_0:G10

dff_0_3:G13

dff_0_2:G12

输入文件 2:

G13

G11

G12

G10

N_25

输出文件 1:

dff_0_3:G13

dff_0_1:G11

dff_0_2:G12

dff_0:G10

dff_0_5:N_25

这是我写的 perl 代码,但它没有像我希望的那样工作。

my @input_file2 = <IN2>;

chomp @input_File2;

while (<input_file1>) {

foreach my $i (0..$#input_File2){

print OUT43 if /(.+)\:\Q$input_File1[$i]\E/; 

}

}

close (IN33);

close (IN43);

close (OUT43);

您的代码中有很多错误。

  1. 你声明了我的@input_file2 数组,但是 chomp @input_File2
  2. 你的 while (<input_file1>) { 的 "input_file1" 是文件句柄吗?
  3. 你 foreach $#input_File2,但在正则表达式中使用 $input_File1。
  4. 你应该在 file2 的循环中循环 file1

我对你的代码做了一点改动:

            #!/usr/bin/perl

            open (IN33, "<1.txt") or die "can't open file 1.txt";
            open (IN43, "<2.txt") or die "can't open file 2.txt";
            open (OUT43, ">out.txt") or die "can't open file out.txt";

            my @input_file2 = <IN43>;
            my @input_file1 = <IN33>;

            chomp @input_file2;


            foreach my $i (@input_file2){
            foreach (@input_file1) {

            print OUT43 if /(.+)\:\Q$i\E/;

            }

            }

            close (IN33);

            close (IN43);

            close (OUT43);

使用grep来完成。 grep returns 数组中的匹配元素,然后构建列表以存储 grep 的输出。使用 select 将打印语句的内容写入新文件。

使用词法文件处理程序时无需关闭文件

open my $fh1, "<", "one.txt";
open my $fh2 , "<","two.txt";
open my $wh, ">","output.txt";
my @data1 = <$fh1>;
select ($wh);

while (my $line = <$fh2>)
{
    chomp $line;
    my ($sort_data) = grep{/$line$/} @data1;
    print "$sort_data";
}