How to use a variable value as a glob template in Perl?

In Perl, you can get a list of files matching the pattern:

my @list = <*.txt>;
print  "@list";

Now, I would like to pass the template as a variable (because it passed into the function). But this does not work:

sub ProcessFiles {
  my ($pattern) = @_;
  my @list = <$pattern>;
  print  "@list";
}

readline() on unopened filehandle at ...

Any suggestions?

+5
source share
4 answers

Use glob :

use strict;
use warnings;

ProcessFiles('*.txt');

sub ProcessFiles { 
  my ($pattern) = @_; 
  my @list = glob $pattern;
  print  "@list"; 
} 

Here is an explanation why you get a warning from I / O operators :

, , (, $foo), ... , glob ($ foo), , , .)

+12

?

my @list = <*.txt>;
ProcessFiles(\@list);

sub ProcessFiles {
    my $list_ref = shift;
    for my $file ( @{$list_ref} ) {
        print "$file\n";
    }
}
0
use File::Basename;
@ext=(".jpg",".png",".others");
while(<*>){
 my(undef, undef, $ftype) = fileparse($_, qr/\.[^.]*/);
 if (grep {$_ eq $ftype} @ext) {
  print "Element '$ftype' found! : $_\n" ;
 }
}
0
source

How to wrap it with the command "eval"? Like this...

sub ProcessFiles {
  my ($pattern) = @_;
  my @list;
  eval "\@list = <$pattern>";
  print @list;
}
-1
source

All Articles