看起来很简单的一段代码显然并没有按照我想要的去做.
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"; }在我的测试案例中,该目录确实存在并且为空.但是,触发了if的then(第一)部分,而不是预期的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返回假阳性
发布评论