I have a code that is able to read two files as input and make a comparison between the two writing matching elements in the output. Let's consider the $list\_file readen by my script as a fixed list used to chose elements from the $data\_file. I'm trying to make this script looping in a folder and reading multiple data\_files with a specific name pattern, but I'm getting an error and I'm not able to solve it.

Here is my list\_file named "list.txt":

```
X1 A B
X2 C D
X3 E F

```

And my first data\_file named "data\_file1.txt":

```
A X1 2 5
B X1 3 7
C X2 1 4
D X2 1 5

```

And my second data\_file named "data\_file2.txt":

```
E X3 5 7
F X3 3 4
G X4 2 3
H X4 2 5

```

I would like to obtain an output that looks like this:

```
X1 A B 2 5 3 7
X2 C D 1 4 1 5
X3 E F 5 7 3 4

```

Both my data\_files are in a folder that contains also other files, so I need to match "data" as pattern to recognize the correct inputs.

And this is my code:

```
my $list_file = "list.txt";
my $dirname = "data_directory";
my $dh;

use strict;
use warnings;
use autodie;
use feature 'say';  

opendir ($dh, $dirname) || die "Impossible open the $dirname!";
while (my $data_file = readdir ($dh)){
    if ("$dh/$data_file" =~ /data/){

        open my $data_fh, "<", $data_file;
        my %data;
        while (<$data_fh>) {
            chomp;
            my ($id2, $id1, @data) = split /\t/;
            $data{$id1}{$id2} = \@data;
        }

        open my $list_fh, "<", $list_file;
        LINE: while(<$list_fh>) {
            chomp;
            my ($id1, @id2s) = split /\t/;
            my $data_id1 = $data{$id1};
            defined $data_id1 or next LINE;  

            my @values = map @{ $data_id1->{$_} }, @id2s;  
            say join "\t", $id1, @id2s, @values;
        }
    }
}
closedir (DIR);

```

If I run this code I get the right result only for the first data\_file. Moreover I get this error:

```
"Can't open 'data_file2.txt' for reading: 'No such file or directory' at code.pl line 23"

```

Suggestions are welcome!