如何在 Perl 中使用变量的值作为 glob 模式?

发布于 2024-08-21 07:31:49 字数 319 浏览 10 评论 0原文

在 Perl 中,您可以获得与模式匹配的文件列表:

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

现在,我想将模式作为变量传递(因为它被传递到函数中)。但这不起作用:

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

readline() on unopened filehandle at ...

有什么建议吗?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

心病无药医 2024-08-28 07:31:49

使用 glob

use strict;
use warnings;

ProcessFiles('*.txt');

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

以下是为什么收到警告的解释,来自 I/O 运算符

如果尖括号包含的是
一个简单的标量变量(例如,
$foo),那么该变量包含
要输入的文件句柄的名称
从...直接调用内部函数作为 glob($foo) 被认为更干净,这可能是首先完成它的正确方法。)

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

清浅ˋ旧时光 2024-08-28 07:31:49

为什么不将文件列表的数组引用传递给函数?

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

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

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";
    }
}
水晶透心 2024-08-28 07:31:49
use File::Basename;
@ext=(".jpg",".png",".others");
while(<*>){
 my(undef, undef, $ftype) = fileparse($_, qr/\.[^.]*/);
 if (grep {$_ eq $ftype} @ext) {
  print "Element '$ftype' found! : $_\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" ;
 }
}
独享拥抱 2024-08-28 07:31:49

用“eval”命令包装它怎么样?像这样...

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

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

sub ProcessFiles {
  my ($pattern) = @_;
  my @list;
  eval "\@list = <$pattern>";
  print @list;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文