Perl Glob返回假阳性 [英] Perl glob returning a false positive

查看:57
本文介绍了Perl Glob返回假阳性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来很简单的一段代码显然并没有按照我想要的去做.

What seemed liked a straightforward piece of code most certainly didn't do what I wanted it to do.

有人可以向我解释它的作用以及为什么吗?

Can somebody explain to me what it does do and why?

my $dir = './some/directory';

if ( -d $dir && <$dir/*> ) {
    print "Dir exists and has non-hidden files in it\n";
}
else {
    print "Dir either does not exist or has no non-hidden files in it\n";
}

在我的测试案例中,该目录确实存在并且为空.但是,触发了ifthen(第一)部分,而不是预期的else部分.

In my test case, the directory did exist and it was empty. However, the then (first) section of the if triggered instead of the else section as expected.

我不需要任何人建议如何完成我想完成的工作.我只想了解Perl对这段代码的解释,这肯定与我的不匹配.

I don't need anybody to suggest how to accomplish what I want to accomplish. I just want to understand Perl's interpretation of this code, which definitely does not match mine.

推荐答案

使用 glob (又名<filepattern>)使其成为迭代器;每次调用一次,它都会返回一个文件,并且在完成对初始结果的迭代之前,不会响应模式的更改(例如,不同的$ dir);我怀疑这会引起您的麻烦.

Using glob (aka <filepattern>) in a scalar context makes it an iterator; it will return one file at a time each time it is called, and will not respond to changes in the pattern (e.g. a different $dir) until it has finished iterating over the initial results; I suspect this is causing the trouble you see.

简单的答案是始终在列表上下文中使用它,就像这样:

The easy answer is to always use it in list context, like so:

if( -d $dir && ( () = <$dir/*> ) ) {

glob可能仅在标量上下文中真正安全地使用,如果您完全确定,将在代码中执行多次,如果尝试 ,则在尝试开始新的迭代之前将耗尽迭代器.在大多数情况下,完全避免在标量上下文中出现glob更容易.

glob may only really be used safely in scalar context in code you will execute more than once if you are absolutely sure you will exhaust the iterator before you try to start a new iteration. Most of the time it's just easier to avoid glob in scalar context altogether.

这篇关于Perl Glob返回假阳性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆