开发者

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

开发者 https://www.devze.com 2022-12-19 23:59 出处:网络
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 tha

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) = 开发者_Python百科@_;
  my @list = <$pattern>;
  print  "@list";
}

readline() on unopened filehandle at ...

Any suggestions?


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


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";
    }
}


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


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

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

精彩评论

暂无评论...
验证码 换一张
取 消