[英]Why does opening an undef not fail?
這段代碼就像我期望的那樣死掉:
use strict;
use warnings;
open my $fh, "<", "" or die $!;
但這不是:
use strict;
use warnings;
open my $fh, "<", undef or die $!;
這里發生了什么?
open函數有很多小怪癖,這是其中之一:
作為特殊情況,三參數形式具有讀/寫模式,第三個參數為“undef”:
open(my $tmp, "+>", undef) or die ...
打開一個匿名臨時文件的文件句柄。 同樣使用“+ <”用於對稱,但你真的應該考慮先寫一些東西到臨時文件。 你需要尋求()來做閱讀。
雖然,正如評論中的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);
}
}
顯然,文檔在11月的blead perl中得到了修復 :
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.