Perl Glob返回假阳性

编程入门 行业动态 更新时间:2024-10-10 02:15:39
本文介绍了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"; }

在我的测试案例中,该目录确实存在并且为空.但是,触发了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

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返回假阳性

本文发布于:2023-11-29 10:49:44,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646178.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:阳性   Perl   Glob

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!