Home > database >  Perl glob returning false positive when trying to match specific file types
Perl glob returning false positive when trying to match specific file types

Time:12-10

I am trying to match either "program.log" or "program.log.gz" or both in a directory using glob but glob is returning both string to @array regardless if anyone of them exist.

I did

@array = glob ("$dir/program.{log,log.gz}");

And now @array contains

$dir/program.log
$dir/program.log.gz

regardless if they actually exist.

Seems like glob is just expanding the string and pass it to @array regardless if the file actually exist. Is this an intended behaviour for glob? If so how do I pass only filenames that exists to @array?

CodePudding user response:

This is documented behaviour of glob:

If non-empty braces are the only wildcard characters used in the glob, no filenames are matched, but potentially many strings are returned. For example, this produces nine strings, one for each pairing of fruits and colors:

my @many = glob "{apple,tomato,cherry}={green,yellow,red}";

If you wanted to pass only existing files to the array, you could use grep and a file test, such as -e (exists)

my @files = grep -e, glob ("$dir/program.{log,log.gz}");
  •  Tags:  
  • perl
  • Related