您的位置:首页 > 其它

perl中子程序的运用,以及在子程序中变量进行私有(my)声明的重要性 .

2013-01-01 11:19 441 查看
我们都知道用my可以来定义私有变量,这个可以在很多情况下防止错误的发生,下面我们通过一个例子来看一看。

下面是一个转换程序,也就是简单的把DNA序列中的A转变成T,第一种情况没有使用私有变量。如下:

[plain]
view plaincopyprint?

#下面是一段DNA序列 $DNA=ATTATATAT;#这里是我们的序列 $result=A_to_T($DNA); print "I changed all $DNA A to T, and the we get the result $result\n\n"; sub A_to_T { my ($input)=@_; $DNA=$input;#没有使用私有变量 $DNA=~s/A/T/g; return $DNA; }
#下面是一段DNA序列
$DNA=ATTATATAT;#这里是我们的序列
$result=A_to_T($DNA);
print "I changed all $DNA A to T, and the we get the result $result\n\n";

sub A_to_T
{
my ($input)=@_;
$DNA=$input;#没有使用私有变量
$DNA=~s/A/T/g;
return $DNA;
}


结果如下:

[plain]
view plaincopyprint?

F:\>perl\a.pl I changed all TTTTTTTTT A to T, and the we get the result TTTTTTTTT F:\>
F:\>perl\a.pl
I changed all TTTTTTTTT A to T, and the we get the result TTTTTTTTT

F:\>


这里我们发现$DNA的值变成了TTTTTTTTT,而不是以前ATTATATAT。这是因为在子程序中,我们使用了同样的$DNA 变量,而在子程序中它的值已经被改变了。所以输出的时候就是改变以后的值。

下面我们把子程序中的$DNA 进行私有变量声明:

程序如下:

[plain]
view plaincopyprint?

#下面是一段DNA序列 $DNA=ATTATATAT; $result=A_to_T($DNA); print "I changed all $DNA A to T, and the we get the result $result\n\n"; sub A_to_T { my ($input)=@_; my $DNA=$input; $DNA=~s/A/T/g; return $DNA; }
#下面是一段DNA序列
$DNA=ATTATATAT;
$result=A_to_T($DNA);
print "I changed all $DNA A to T, and the we get the result $result\n\n";

sub A_to_T
{
my ($input)=@_;
my $DNA=$input;
$DNA=~s/A/T/g;
return $DNA;
}


结果如下:

[plain]
view plaincopyprint?

F:\>perl\a.pl I changed all ATTATATAT A to T, and the we get the result TTTTTTTTT F:\>
F:\>perl\a.pl
I changed all ATTATATAT A to T, and the we get the result TTTTTTTTT

F:\>


这样就正常了。

当然你可以说,我们在子程序中可以完全不用$DNA这一个变量,就如同下面一样:

[plain]
view plaincopyprint?

#下面是一段DNA序列 $DNA=ATTATATAT; $result=A_to_T($DNA); print "I changed all $DNA A to T, and the we get the result $result\n\n"; sub A_to_T { my ($input)=@_; $dna_to_change=$input; $dna_to_change=~s/A/T/g; return $dan_to_change; }
#下面是一段DNA序列
$DNA=ATTATATAT;
$result=A_to_T($DNA);
print "I changed all $DNA A to T, and the we get the result $result\n\n";

sub A_to_T
{
my ($input)=@_;
$dna_to_change=$input;
$dna_to_change=~s/A/T/g;
return $dan_to_change;
}


得到的也是正常的结果:

[plain]
view plaincopyprint?

F:\>perl\a.pl I changed all ATTATATAT A to T, and the we get the result F:\>
F:\>perl\a.pl
I changed all ATTATATAT A to T, and the we get the result

F:\>


但是,没有人能够保证你不会一时糊涂,在子程序用了程序中的变量。或者当你第一次使用的时候,可以避免,当你过来几个月以后回过头再来使用的时候,就不能保证完全正确了,所以为了你代码的通用性,我们还是在所有的子程序中使用my私有变量吧!

原文见:http://blog.csdn.net/gaorongchao1990626/article/details/8022712
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐