Pass Filehandle and scope

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

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值