Frank
Frank

Reputation: 66174

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?

Upvotes: 5

Views: 6617

Answers (4)

ghostdog74
ghostdog74

Reputation: 342363

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

Upvotes: 0

toolic
toolic

Reputation: 62037

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

Upvotes: 12

Alan Haggai Alavi
Alan Haggai Alavi

Reputation: 74232

Why not pass the array reference of the list of files to the function?

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

sub ProcessFiles {
    my $list_ref = shift;
    for my $file ( @{$list_ref} ) {
        print "$file\n";
    }
}

Upvotes: 0

Robert Wohlfarth
Robert Wohlfarth

Reputation: 1771

What about wrapping it with an "eval" command? Like this...

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

Upvotes: -1

Related Questions