I want to read and save the content of a file in a hash of array. The first column of each row would be the key. Then, I want to read the files in a directory and add the file name to the end of the array according to the key!
file ($file_info)
AANB John male
S00V Sara female
SBBA Anna female
files in the directory:
AANB.txt
SBBA.txt
S00V.txt
expected output:
AANB John male AANB.txt
S00V Sara female S00V.txt
SBBA Anna female SBBA.txt
Here's the script itself:
#!/usr/bin/perl
use strict;
use warnings;
my %all_samples=();
my $file_info = $ARGV[0];
open(FH, "<$file_info");
while(<FH>) {
chomp;
my @line = split("\t| ", $_);
push(@{$all_samples{$line[0]}}, $_);
}
my $dir = ".";
opendir(DIR, $dir);
my @files = grep(/\.txt$/,readdir(DIR));
closedir(DIR);
foreach my $file (@files) {
foreach my $k (keys %all_samples){
foreach my $element (@{ $all_samples{$k} }){
my @element = split(' ', $element);
if ($file =~ m/$element[0]/) {
push @{$all_samples{$element}}, $file;
}
else {
next;
}
}
}
}
foreach my $k (keys %all_samples) {
foreach my $element (@{ $all_samples{$k} }) {
print $element,"\n";
}
}
But the output is not what I expected
AANB John male
SBBA.txt1
S00V Sara female
SBBA Anna female
S00V.txt1
AANB.txt1