小编Rob*_*Rob的帖子

为什么Perl文件glob()在标量上下文中不在循环外工作?

根据文件globbing的Perl文档,<*>运算符或glob()函数在标量上下文中使用时,应遍历匹配指定模式的文件列表,每次调用时返回下一个文件名或没有更多文件时的undef.

但是,迭代过程似乎只能在循环内工作.如果它不在循环中,那么它似乎在读取所有值之前立即重新开始.

从Perl文档:

在标量上下文中,glob遍历此类文件名扩展,在列表耗尽时返回undef.

http://perldoc.perl.org/functions/glob.html

但是,在标量上下文中,运算符在每次调用时返回下一个值,或者在列表用完时返回undef.

http://perldoc.perl.org/perlop.html#I/O-Operators

示例代码:

use warnings;
use strict;

my $filename;

# in scalar context, <*> should return the next file name
# each time it is called or undef when the list has run out

$filename = <*>;
print "$filename\n";
$filename = <*>;      # doesn't work as documented, starts over and
print "$filename\n";  # always returns the same file name
$filename = <*>;
print "$filename\n";

print "\n";

print "$filename\n" while $filename = <*>; # works in …

perl glob perl5.10

10
推荐指数
2
解决办法
2030
查看次数

标签 统计

glob ×1

perl ×1

perl5.10 ×1