perl变量使用范围非常经典详解

下面的代码以及代码执行结果还有最后的详细说明,希望能帮助大家理解变量在perl中的使用范围。谢谢大家的支持!

#!/bin/perl
$global = "i'm the global version";

showme('at start');
lexical();
localized();
showme('at end');
sub showme
        {
        my $tag = shift;
        print "$tag: $global\n";
        }
sub lexical
        {
        my $global = "i'm in the lexical version";
        print "in lexical() ,\$global is ---> $global\n";
        our $global;
        print "in lexical() with our,\$global is ---> $global\n";
        showme('from lexical()');
        localized();
        }
sub localized
        {
        local $global = "i'm in the localized version";
        print "in localized(),\$global is ---> $global\n";
        showme('from localized');
        }
[root@stationx variable]# perl global.pl
at start: i'm the global version
in lexical() ,$global is ---> i'm in the lexical version
in lexical() with our,$global is ---> i'm the global version
from lexical(): i'm the global version
in localized(),$global is ---> i'm in the localized version
from localized: i'm in the localized version
in localized(),$global is ---> i'm in the localized version
from localized: i'm in the localized version
at end: i'm the global version
[root@stationx variable]#
变量的范围
规则1. global定义了全局变量gv,变量在程序内所有地方可见(特例除外)。
规则2. 如果在父程序内定义了额外的子程序,并且子程序中使用my定义了一个与global变量相同名称的变量gv,那么,在该子程序内变量gv的value是my gv的值,而不是global gv的值。但是,当程序代码从子程序跳转到父程序的时候,程序所使用的gv的值是global gv的值。
规则3. 如果在父程序内定义了额外的子程序,并且子程序中使用了local定义了一个与global变量相同名称的变量gv,那么,知道该子程序结束所使用的变量gv的值都是local gv的值。
规则4. 如果在父程序中定义了额外的子程序,并且在子程序中使用了my定义的一个与global变量名称相同的变量,但是该子程序并不想使用my定义的变量值而想使用global定义的变量值,那么可以使用our重声该变量即可,子程序后续使用的gv的值都是global gv的值。
但是,如果将规则2继续套用在规则4中,规则3的local gv仍然是最具影响力的,依然使用规则3中子程序定义的local gv的值。而不是使用global gv的值。

你可能感兴趣的:(变量,局部变量,perl,全局变量)