【问题标题】:Why does opening an undef not fail?为什么打开undef不会失败?
【发布时间】:2017-09-17 05:16:44
【问题描述】:

此代码如我所料那样死亡:

use strict;
use warnings;

open my $fh, "<", "" or die $!;

但这不是:

use strict;
use warnings;

open my $fh, "<", undef or die $!;

这是怎么回事?

【问题讨论】:

    标签: perl undef


    【解决方案1】:

    open 函数有很多小怪癖,这就是其中之一:

    作为一种特殊情况,具有读/写模式的三参数形式和 第三个参数是“undef”:

    open(my $tmp, "+>", undef) or die ...
    

    打开一个匿名临时文件的文件句柄。也使用“+

    虽然,正如 cmets 中的 ysth 所指出的,文档强烈建议这应该只发生在“++”模式下。我相信这是实现行为的代码。它不检查模式。我不知道这是否是一个错误,但会在与 P5P 交谈后反馈。

    PerlIO *
    PerlIO_openn(pTHX_ const char *layers, const char *mode, int fd,
                 int imode, int perm, PerlIO *f, int narg, SV **args)
    {
        if (!f && narg == 1 && *args == &PL_sv_undef) {
            if ((f = PerlIO_tmpfile())) {
                if (!layers || !*layers)
                    layers = Perl_PerlIO_context_layers(aTHX_ mode);
                if (layers && *layers)
                    PerlIO_apply_layers(aTHX_ f, mode, layers);
            }
        }
    

    显然,文档是fixed in blead perl in November

    diff --git a/pod/perlfunc.pod b/pod/perlfunc.pod
    index 18bb4654e1..1e32cca6dd 100644
    --- a/pod/perlfunc.pod
    +++ b/pod/perlfunc.pod
    @@ -4405,9 +4405,9 @@ argument being L<C<undef>|/undef EXPR>:
    
         open(my $tmp, "+>", undef) or die ...
    
    -opens a filehandle to an anonymous temporary file.  Also using C<< +< >>
    -works for symmetry, but you really should consider writing something
    -to the temporary file first.  You will need to
    +opens a filehandle to a newly created empty anonymous temporary file.
    +(This happens under any mode, which makes C<< +> >> the only useful and
    +sensible mode to use.)  You will need to
     L<C<seek>|/seek FILEHANDLE,POSITION,WHENCE> to do the reading.
    
     Perl is built using PerlIO by default.  Unless you've
    

    【讨论】:

    • 是的,这就是正在发生的事情,但文档似乎是错误的,因为这显然不是读/写模式
    • 读/写模式为+&gt;,第三个参数为undef。只是措辞不佳
    • 嗯,好点@ysth,我愤怒地掩盖了它。我把它读作读或写模式,但很明显它是用于读+写或写+读模式。所以,这要么是一个错误,要么是记录不充分。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2014-10-07
    • 2020-08-02
    • 2021-12-10
    • 2016-02-10
    • 1970-01-01
    相关资源
    最近更新 更多