The Application of Perl Subprogram and the Importance of Variable Private (my) Declarations in Subprogram

Time:2019-7-31

A conversion program that simply converts A into T in a DNA sequence does not use private variables in the first case.

Copy codeThe code is as follows:
#!/bin/perl
# Here is a DNA sequence.
DNA = ATTATATATAT; Here is our sequence.
$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)[email protected]_; 
$DNA=$input; # No private variables are used
   $DNA=~s/A/T/g; 
   return $DNA; 
}

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

F:\> 
Here we find that the value of $DNA becomes TTTTTTT instead of ATTATATAT. This is because in the subroutine, we use the same $DNA variable, and its value has been changed in the subroutine. So the output is to change the value later.

Here’s a private variable declaration for $DNA in the subroutine:

Copy codeThe code is as follows:
#!/bin/perl
# Here is a DNA sequence.
$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)[email protected]_; 
   my $DNA=$input; 
  $DNA=~s/A/T/g; 
  return $DNA; 
}

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

F:\>

That’s normal.

Of course, you can say that the variable of $DNA can be completely eliminated in subroutines, just like the following:

Copy codeThe code is as follows:
#!/bin/perl
# Here is a DNA sequence.
$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)[email protected]_; 
   $dna_to_change=$input; 
   $dna_to_change=~s/A/T/g; 
   return $dan_to_change; 
}

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

F:\>

However, no one can guarantee that you won’t be confused for a while by using variables in the subroutine. Or when you use it for the first time, it can be avoided. When you come back to use it in the past few months, you can’t guarantee that it’s completely correct. So for the sake of code universality, use my private variable in all subroutines.

Recommended Today

JS Engineering

Project tools modularization JS module specification CommonJS·AMD·CMD·UMD·ES6 project management Lint Code review efficiency tool Eslint scheme official:https://cn.eslint.org/docs/us… airbnb : https://github.com/airbnb/jav… standard : https://github.com/standard/e… Multi packet mode Introduction to multi package management tool pack Webpack4 project structure deploy