See the code sample below.
sub main {
useFH(createFH($p));
}
sub createFH($) {
print "Debug, opening ${_[0]}\n";
# it will be an error if you have the file handler as
# declared as local *FH;
# e.g. { don't do this }
# local *FH;
# instead, do this
# open FH, "> ${_[0]}";
# return \*FH
# or you can do this
# my $fh;
# open $fh, "> ${_[0]};"
# return $fh;
# however, doing this you may get
# print() on closed filehandle ...
# it could because the FileHandler will be closed on exiting scope?
# Seems that we shall use the Tie Variables?
#
open FH, "> ${_[0]}";
return \*FH;
}
# you can also write the proto as follow
# sub useFH($)
sub useFH(*) {
my ($fh) = @_;
# local *FH = shift;
print $fh "hello world";
}
the reason could be that if FH is declared as local scope, then after the function createFH exits, the FH handle will be destroyed. which cause the Handle to be closed....
While if you use the Bare word FH as the FileHandle, then it will not be closed on Function createFH exits.
So the suggestion, there are two solutions
1. create your own tie variable
2. create the handle on the parent function, passed to the callee function
本文探讨了Perl中文件句柄的正确管理方法,包括如何避免因局部作用域导致的句柄提前关闭问题。提供了两种解决方案:一是创建自定义的Tie变量;二是将句柄在父函数中创建并传递给子函数。

被折叠的 条评论
为什么被折叠?



