曲径通幽论坛

标题: 子例程和句柄的引用 [打印本页]

作者: beyes    时间: 2011-10-25 15:00
标题: 子例程和句柄的引用
匿名子例程
在 sub 关键字后省略掉子例程的名字,那么就是一个匿名子例程,注意匿名子例程的函数体后面要以一个分号结尾。下面例子简单演示引用一个匿名子例程:
[code=perl]#!/usr/bin/perl

my $subref = sub { print @_; };

&$subref('a', 'b', 'c');
print "\n";
[/mw_shl_code]
运行输出:
./anoysub.pl
abc

文件句柄的引用
将文件句柄传递给子例程的惟一途径就是通过引用的传递。这里演示两种方式:

方式一
[code=perl]#!/usr/bin/perl

open (HD, "<hello.txt") || die "Can not open file: $!";     #以只读方式打开文件 hello.txt,并建立相应句柄 HD

&readit (*HD);

sub readit {
        local(*myfile) = @_;       #给本地别名 myfile 赋值,即将别名传递给子例程
        while (<myfile>) {       #别名是文件句柄 HD 的另一个名字,while 循环逐行读取文件句柄中的各行内容
                print;
        }
}[/mw_shl_code]
运行输出:
]$ ./subquote.pl
hello world
hello perl
hello cpp

方式二
[code=perl]#!/usr/bin/perl
open (HD, "<hello.txt") || die "Can not open file: $!";

&readit (\*HD);

sub readit {
        my ($myfile) = @_;
        while (<$myfile>) {
                print;
        }
}[/mw_shl_code]
运行输出:
]$ ./subquote.pl
hello world
hello perl
hello cpp

方式一是符号引用,方式二相当硬引用。在 @_ 赋值给函数体内的 myfile 时,写法也不相同。方式一是 glob 类型,方式二是一个标量。




欢迎光临 曲径通幽论坛 (http://www.groad.net/bbs/) Powered by Discuz! X3.2