当前位置: 移动技术网 > IT编程>网页制作>Perl > perl子程序的运用及子程序中变量私有(my)声明的重要性

perl子程序的运用及子程序中变量私有(my)声明的重要性

2017年12月08日  | 移动技术网IT编程  | 我要评论

一个转换程序,简单的把dna序列中的a转变成t,第一种情况没有使用私有变量。

复制代码 代码如下:

#!/bin/perl
#下面是一段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; 
}

结果如下:
f:\>perl\a.pl 
i changed all ttttttttt a to t, and the we get the result ttttttttt 

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

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

复制代码 代码如下:

#!/bin/perl
#下面是一段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; 
}

结果如下:
f:\>perl\a.pl 
i changed all attatatat a to t, and the we get the result ttttttttt

f:\>

这样就正常了。

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

复制代码 代码如下:

#!/bin/perl
#下面是一段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; 
}

得到的也是正常的结果:
f:\>perl\a.pl 
i changed all attatatat a to t, and the we get the result 

f:\>

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网