how to print files name having same name just a character difference in perl

时间:2015-06-30 13:48:34

标签: perl

I have files in folder named SRR1425702_1.txt, SRR1425702_2.txt, SRR1425709_1.txt, SRR1425709_2.txt. I want to print the files with the same prefix (the part before _) on the same line, separated by tabs.

SRR1425702_1.txt<TAB>SRR1425702_2.txt
SRR1425709_1.txt<TAB>SRR1425709_2.txt

1 个答案:

答案 0 :(得分:1)

分组通常使用哈希进行。

my %files_by_prefix;
for my $file (@files) {
   my ($prefix) = $file =~ /^([^_]+)_/
      or next;

   push @{ $files_by_prefix{$prefix} }, $file;
}

for my $prefix (sort keys %files_by_prefix) {
   print(join("\t", sort @{ $files_by_prefix{$prefix} }), "\n");
}