Solutions to some Perl scripts

Here I post some scripts, with comments: minimum and maximum, reverse complement a sequence and reverse and complement a sequence stored into a file.

3.1. Minimum and maximum (and average)

#!/usr/bin/perl
 
# This scripts takes a list of numbers as input, returns minimum and maximum
# the list is stored by Perl in the @ARGV variable
 
# First: let's exit from the script if no arguments were supplied 
# by the user
if ($#ARGV < 1) {
   die " Please, enter a list of numbers as arguments of this script.\n";
}
 
# Second: initialize a $min and $max variables
# using the first element of the @ARGV array
$min   = $ARGV[0];
$max   = $ARGV[0];
 
# Third: now we will cycle through the nubmers of @ARGV and 
# update $max and $min. 
foreach $number (@ARGV) {
   if ($number > $max) {
      $max = $number;
   }
   if ($number < $min) {
      $min = $number;
   }
 
   # This is for average calculation
   $sum+=$number;
   $count=$count+1;
}
 
 
$average = $sum/$count;
 
print "
You typed $count numbers.
Average  $avg
Minimum  $min
Maximum  $max
";

3.3. Reverse complementary

#!/usr/bin/perl
 
# This scripts takes a sequence as input and
# returns the reverse complementary
 
# To avoid confusion we switch to UPPER CASE
$sequence = uc($ARGV[0]);
 
if (length($sequence)<1) {
	die " Error:\n Please type a sequence...\n";
}
 
$revcompl = reverse($sequence);
$revcompl =~tr/ACGTN/TGCAN/;
 
print "
You sequence    $sequence
Reverse compl   $revcompl
";

Reverse complement a file

Now the difficult task is to note that if you reverse and complement each line you are producing a wrong output.

#!/usr/bin/perl
 
# Reverse complement a sequence stored in a file
# (with multiple lines)
 
$filename = $ARGV[0];
open (I, "$filename") || die " FATAL ERROR: Unable to open $filename\n";
 
while (<I>) {
	# each line ($_) ends with a \n. the "chop" function removes it
	chop($_);
    $sequence.=$_;
}
 
# now proceed as previouse exercise!!!
Tagged , ,

Leave a Reply

Your email address will not be published. Required fields are marked *