How can I use a variable's value as a glob pattern in Perl?
design-patterns, file, glob, perl
Solution
Use glob:
use strict;
use warnings;
ProcessFiles('*.txt');
sub ProcessFiles {
my ($pattern) = @_;
my @list = glob $pattern;
print "@list";
}
Here is an explanation for why you get the warning, from I/O Operators:
If what the angle brackets contain is a simple scalar variable (e.g., $foo), then that variable contains the name of the filehandle to input from... it's considered cleaner to call the internal function directly as glob($foo), which is probably the right way to have done it in the first place.)
Problem
In Perl, you can get a list of files that match a pattern: ``` my @list = <*.txt>; print "@list"; ``` Now, I'd like to pass the pattern as a variable (because it's passed into a function). But that doesn't work: ``` sub ProcessFiles { my ($pattern) = @_; my @list = <$pattern>; print "@list"; } readline() on unopened filehandle at ... ``` Any suggestions?