http://fhqdddddd.blog.163.com/blog/static/1869915420124141527335/


在perl的函数定义中,如果使用文件句柄作为参数进行传递,请使用引用,而不要使用直接的变量赋值操作。原因是如果在其它包中引用这个函数,将导致文件句柄非法错误。

#!/usr/bin/perl
use strict;
use warnings;

sub read_file {
   my $h = shift;
   my @lines = <$h>;
   print @lines;
}

open(FH,"sub_read_file.pl") or die "can not open sub_read_file:$!/n";
my $handle = \*FH;
read_file($handle);
close(FH);


为了将一个文件句柄转换为typeglob引用,只需在其名字前加"\*"
$fh=\ *MY_FH;
typeglob引用能够直接传给subroutine
hello(\*MY_FH);
也能被subroutine返回
my $fh=get_fh();
sub get_fh {
   open (FOO, "foo.txt") or die "foo: $!";
   returen \*FOO;
}
查看一个句柄是否有效
使用fileno()函数
$integer=fileno(FILEHANDLE)
fileno() 函数以字符串的形式,typeglob形式或者typeglob引用形式接受句柄。如果句柄有效,返回文件句柄的文件描述符。STDIN STDOUT STDERR描述符为0 1 2,其他文件句柄具有大于3的文件描述。如果没有有效句柄,fileno()返回undef值。
die="not a filehandle" unless defined fileno($fh);