"0"如何? readdir()导致的结果在一段时间内不为假? [英] How is "0" result from readdir() not false in a while condition?

查看:87
本文介绍了"0"如何? readdir()导致的结果在一段时间内不为假?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

另请参阅:它在文档中的哪儿说明测试readdir是否具有定义性?. (不是重复的;只是紧密相关.)

许多人认为以下循环是惯用的:

Many people treat the loop below as idiomatic:

while (defined(my $file = readdir($dir)) {
    ...
}

代替:

while (my $file = readdir($dir)) {
    ...
}

由于后者的版本,如果文件名只是"0"(零),则它将终止循环,而在没有更多文件时返回"undef".

because supposedly with the latter version if the filename is just "0" (zero) it should terminate the loop, whereas it returns 'undef' when there are no more files.

但是在过去的某个时候,不再需要进行defined()的测试-似乎存在特殊情况的代码,无论使用哪种版本,该代码都可以工作.

However at some point in the past this test for defined() stopped being necessary - there appears to be special case code that allows the latter version to work regardless.

我想知道它是如何工作的?

I'd like to know how this works?

奇怪的是,如果我将对readdir()的调用替换为对foo()的调用:

Curiously,if I replace the call to readdir() with a call to foo() instead:

sub foo
{
    my ($dir) = @_;
    return readdir($dir);
}

while (my $file = foo($dir)) {
    ...
}

然后代码执行即可完成我所期望的工作,并在找到名为"0"的文件时终止循环.

then the code does do what I'd expect, and terminate the loop when a file named "0" is found.

(在MacOS X 10.5.6上使用Perl 5.8.9进行了测试)

(tested with Perl 5.8.9 on MacOS X 10.5.6)

推荐答案

这很神奇.特别是在魔术( perlsyn B::Deparse .这是一个使用速记循环的文件:

It is magic. Specifically while magic (documented in perlsyn, perlop, and probably other places I don't remember). Perl allows you certain shorthand notations. If you want to see what Perl is doing behind your back you can use B::Deparse. Here is a file that uses the shorthand loop:

#!/usr/bin/perl

use strict;
use warnings;

opendir my $dir, "/tmp" or die "$!";

while (my $file = readdir($dir)) {
    print "$file\n";
}

如果运行perl -MO=Deparse filename.pl,您将获得Perl看到的代码:

If you run perl -MO=Deparse filename.pl you get the code Perl sees:

use warnings;
use strict 'refs';
die "$!" unless opendir my $dir, '/tmp';
while (defined(my $file = readdir $dir)) {
    do {
        print "$file\n"
    };
}
filename.pl syntax OK

这篇关于"0"如何? readdir()导致的结果在一段时间内不为假?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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