onlyf onlyf - 7 months ago 12
Perl Question

Perl - Scan directory for pattern in contained filenames and fill array

i ve tried to write a simple function that takes two arguments, input directory and pattern, and returns an array with the matched files that contain the pattern(s) in their name.

my $dir = "/drives/D/Desktop/perlscripts";

sub getfiles
{
my ($dirName, @patterns) = @_;
opendir(my $dir, $dirName) or die "Can't open '$dirName': $!";
my @return;
for my $file (readdir($dir))
{
for my $pattern (@patterns)
{
if ($file =~ /$pattern/)
{
print "$file \n";
push @return, $file;
# This avoids having the file in the result twice
last;
}
}
}

return @return;
}


my @plscripts = getfiles($dir, "pl");
print "@plscripts \n";


I get nothing in STDOUT with the code as is, after some tests, i think the problem is with the.

Edited with changes : As you can see i commented out #last; but yes it matches every file name on every iteration then. So i end up with duplicate entries in the array.

Answer

The quick fix could be add a label for your first loop and then change the "last" to "next FILE":

my $dir = "/drives/D/Desktop/perlscripts";

sub getfiles
{
  my ($dirName, @patterns) = @_;
  opendir(my $dir, $dirName) or die "Can't open '$dirName': $!";
  my @return;
  FILE:
  for my $file (readdir($dir))
  {
    for my $pattern (@patterns)
    {
      if ($file =~ /$pattern/)
      { 
        print "$file \n";
        push @return, $file;
        # This avoids having the file in the result twice
        # last
        next FILE;
      }
    }
   }

    return @return;
  }


 my @plscripts = getfiles($dir, "pl");
 print "@plscripts \n";