曲径通幽论坛

 找回密码
 立即注册
搜索
查看: 3634|回复: 0
打印 上一主题 下一主题

自动加载 AUTOLOAD($TUTOLOAD变量)

[复制链接]

4918

主题

5880

帖子

3万

积分

GROAD

曲径通幽,安觅芳踪。

Rank: 6Rank: 6

积分
34387
跳转到指定楼层
楼主
发表于 2011-10-20 11:46:24 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
下面的所说的子例程和子函数属于同一概念。AUTOLOAD 函数可以检查子函数是否被定义过,如果调用一个没有被定义过的子函数时会自动去调用 AUTOLOAD 子例程,同时还会把未定义的子例程名赋值给特殊内置变量 $AUTOLOAD 。

比如下面代码:
[code=perl]#!/usr/bin/perl


sub AUTOLOAD {
        my (@arguments) = @_;
        $args = join(', ', @arguments);
        print "$AUTOLOAD was never defined.\n";
        print "The arguments passed were $args.\n";
}


$arg1 = "perl";
$arg2 = "world";
$arg3 = 1000;


&notdef($arg1, $arg2, $arg3);[/mw_shl_code]
运行输出:
$ ./autoload.pl
main::notdef was never defined.
The arguments passed were perl, world, 1000.
由输出可见,由于在主函数 main 中调用 notdef 子函数并不存在,所以程序自动去调用了 AUTOLOAD 子函数(函数体可自定义),并且将未定义的子函数 notdef 信息赋值到 $AUTOLOAD 变量中。

测试代码2:
[code=perl]#!/usr/bin/perl

sub AUTOLOAD {
        my (@arguments) = @_;
        my ($package, $command) = split("::", $AUTOLOAD, 2);     #分隔之前是 main::date
        return `$command @arguments`;       #反引号表示使用 shell 来执行命令
}

$day = date("+%D");
print "Today is $day.\n";

print cal(3,2011);[/mw_shl_code]
运行输出:
$ ./auto.pl
Today is 10/20/11
.
     March 2011
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|曲径通幽 ( 琼ICP备11001422号-1|公安备案:46900502000207 )

GMT+8, 2024-5-19 03:22 , Processed in 0.062703 second(s), 22 queries .

Powered by Discuz! X3.2

© 2001-2013 Comsenz Inc.

快速回复 返回顶部 返回列表