Search code examples
perlprintfglob

In perl, is there a terse way to combine glob and printf?


I want @list to contain all the filenames in $root_dir that match *YYYYMMDD*, where YYYYMMDD is 25 hours ago.

I try ...

my ($y, $m, $d) = (localtime(time - 25 * 60 * 60))[5,4,3]; 
my $pattern = sprintf('*%4d%02d%02d*',$y+1900,$m+1,$d);
print "The pattern is $pattern\n"; 
my @files = <$pattern>;
foreach (@files) {
    print "$_\n";
}

... but instead of getting a list of files, I get readline() on unopened filehandle.

I know the <> operator can interpret variables, so <$y$m$d> would work during two-thirds of the days during the last three months of the year because those would be months and days that have two digits, but that is not robust.

Do I have to write ...

$m = sprintf('%02d',$m+1);  
$d = sprintf('%02d',$d+1);
my @files = <*$y$m$d*>;

... or is there something more concise? Something like ...

# invalid code unless you want to produce the string "readline() on unopened filehandle" for some reason
my @files = <sprintf('*%4d%02d%02d*',$y+1900,$m+1,$d)>;

Solution

  • Use

    my @files = glob($pattern);
    

    The <...> operator is way too overloaded already. Specifically, <$...> is taken as a filehandle.