`

Pass Filehandle and scope

    博客分类:
  • perl
阅读更多

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

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics