Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use a variable's value as a glob pattern in Perl?

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?

like image 855
Frank Avatar asked Feb 15 '10 03:02

Frank


1 Answers

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.)

like image 88
toolic Avatar answered Sep 25 '22 07:09

toolic