如何从 Perl 的 STDOUT 取消别名? [英] How do I unalias from Perl's STDOUT?
问题描述
当我运行这个时:
open FP, ">xyz";
my $file = *FP;
printf $file "first\n";
$file = *STDOUT;
printf $file "second\n";
open $file, ">abc";
print $file "third\n";
print STDOUT "fourth\n";
print FP "fifth\n";
第四个"打印不会转到 STDOUT,而是转到abc".
The "fourth" print does not go to STDOUT, rather to "abc".
STDOUT 与 FP 不同,其行为符合预期.
STDOUT is different from FP which behaves as expected.
我做错了什么?我有什么不明白的?
What am I doing wrong? What am I not understanding?
推荐答案
好吧,首先,您错误地使用了打开".
Well, for starters, you're using 'open' wrongly.
open my $fp , '>', 'xyz' ;
是推荐的语法.
强烈建议您不要使用裸露的FP",因为它不是词法.
the bare 'FP' you have there is strongly recommended against, as it is not a lexical.
其次,您将文件指针作为新事物重新打开.这不是一个很好的做法,它不应该是一个问题,但它只是一个坏主意.您应该关闭文件指针或让它超出范围(通过词法).
Secondly, you're re-opening file-pointers as new things. This is not very good practice, it shouldn't be a problem, but its just a bad idea. You should close the file pointer or let it run out of scope ( via a lexical ).
第三,'*STDOUT' 是一个引用.
Thirdly, '*STDOUT' is a reference.
my $fh = *STDOUT;
print "$fh\n"; #prints '*main::STDOUT';
所以当你这样做时:
open $fh, '>abc';
你在做什么
open *STDOUT, '>abc';
如果你之后立即做
print "$fh\n";
你会注意到它仍然打印 *main::STDOUT
;
you will note it still prints *main::STDOUT
;
一些有趣的代码片段可以解决这个问题:
Some interesting code snippets that clear this up:
my $fh = *STDOUT;
open $fh, '<', "foo.txt";
print $fh "hello";
# Filehandle STDOUT opened only for input at (eval 288) line 6.
my $fh = *STDIN;
open $fh, '<', "foo.txt";
print <>;
# contents of foo.txt here
以下是使用 open 的推荐方法:
Here's a recommended way to use open:
sub foo {
my $fh;
open $fh , '<', 'file.txt' or Carp::croak('Cannot Open File.txt');
# do stuff with $fh;
close $fh or Carp::carp('Something annoying in close :S ');
}
请注意,如果您省略关闭,则一旦 $fh 不可见,该文件将立即关闭.
Note that if you omit close, the file will be closed as soon as $fh goes out of visibility.
这篇关于如何从 Perl 的 STDOUT 取消别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!