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

来源:互联网 发布:java 线程池自动关闭 编辑:程序博客网 时间:2024/06/05 09:19

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

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

[plain] view plaincopyprint?
  1. #下面是一段DNA序列  
  2. $DNA=ATTATATAT;#这里是我们的序列  
  3. $result=A_to_T($DNA);  
  4. print "I changed all $DNA A to T, and the we get the result $result\n\n";  
  5.   
  6. sub A_to_T   
  7. {  
  8.     my ($input)=@_;  
  9.     $DNA=$input;#没有使用私有变量  
  10.     $DNA=~s/A/T/g;  
  11.     return $DNA;  
  12. }  

结果如下:

[plain] view plaincopyprint?
  1. F:\>perl\a.pl  
  2. I changed all TTTTTTTTT A to T, and the we get the result TTTTTTTTT  
  3.   
  4.   
  5. F:\>  

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



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

程序如下:

[plain] view plaincopyprint?
  1. #下面是一段DNA序列  
  2. $DNA=ATTATATAT;  
  3. $result=A_to_T($DNA);  
  4. print "I changed all $DNA A to T, and the we get the result $result\n\n";  
  5.   
  6. sub A_to_T   
  7. {  
  8.     my ($input)=@_;  
  9.     my $DNA=$input;  
  10.     $DNA=~s/A/T/g;  
  11.     return $DNA;  
  12. }  

结果如下:

[plain] view plaincopyprint?
  1. F:\>perl\a.pl  
  2. I changed all ATTATATAT A to T, and the we get the result TTTTTTTTT  
  3.   
  4.   
  5. F:\>  

这样就正常了。


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

[plain] view plaincopyprint?
  1. #下面是一段DNA序列  
  2. $DNA=ATTATATAT;  
  3. $result=A_to_T($DNA);  
  4. print "I changed all $DNA A to T, and the we get the result $result\n\n";  
  5.   
  6. sub A_to_T   
  7. {  
  8.     my ($input)=@_;  
  9.     $dna_to_change=$input;  
  10.     $dna_to_change=~s/A/T/g;  
  11.     return $dan_to_change;  
  12. }  

得到的也是正常的结果:

[plain] view plaincopyprint?
  1. F:\>perl\a.pl  
  2. I changed all ATTATATAT A to T, and the we get the result  
  3.   
  4.   
  5. F:\>  


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

 

原文见:http://blog.csdn.net/gaorongchao1990626/article/details/8022712

原创粉丝点击