Subroutines

Presenter Notes

Subroutines

  • subroutines are blocks of code that can be reused
  • start with sub and have a name and then are enclosed in code block of {}

    1 sub a_routine {
    2     my @args = @_; # the arguments passed in are avaialable as @_;
    3     print "the arguments are ", join(",", @args), "\n";
    4 }
    5 # here is code to call this subroutine
    6 &a_routine('a','b','c');
    
  • Not required to define the subroutine before you use it, so you can writ all your subroutines at the bottom of your file

  • Or store in a separate file and bring in with require

Presenter Notes

Subroutine arguments

  • Input to a subroutine is always a list, if you want to have some things stay grouped, you must use references.

     1 # 
     2 &evaluate( qw(a b c), qw(Z Y X));
     3 
     4 &evaluate( [qw(a b c)], [qw(Z Y X)]);
     5 sub evaluate {
     6     my @arguments = @_;
     7     print "1st arg is: $_[0] second arg is $_[1]\n";
     8     # really you expect it to be used in the second way
     9     my $dataset1 = $_[0];
    10     my $dataset2 = $_[0]
    11 }
    

Presenter Notes

Modules

  • Collections of subroutines.

  • Allow association of data in structures

  • Object-Oriented programming support

Presenter Notes

Getopt::Long module

Command line operated programs traditionally take their arguments from the command line, for example filenames. Besides arguments, these programs often take command line options as well. Options are not necessary for the program to work, hence the name 'option', but are used to modify its default behavior.

$ grep -i 'AACA' DNA.txt > capture.txt
$ make_fake_fasta.pl --length 100

Presenter Notes

script using Getopt::Long

 1 #!/usr/bin/env perl 
 2 use strict;
 3 use warnings;
 4 use Getopt::Long;
 5 my $length = 30;
 6 my $number = 10;
 7 my $help;
 8 GetOptions('l|length:i' => \$length,
 9            'n|number:i' => \$number,
10            'h|help' => \$help);
11 my $usage = "make_fake_fasta.pl - generate random DNA seqs
12 Options:
13 -n <number> the number of sequences to make (default: 10)
14 -l <length> the length of each sequence (default: 30)
15 ";
16 die $usage if $help;
17 my @nucs = qw(A C T G);
18 for (my $i = 1; $i <= $number; $i++) {
19     my $seq;
20     for (my $j = 1; $j <= $length; $j++) {
21         my $index = int(rand (4));
22         my $nuc = $nucs[$index];
23         $seq .= $nuc;
24     }
25     print ">fake$i\n";
26     print $seq, "\n";
27 }

Presenter Notes

List::Util module

1 use List::Util qw(shuffle sum);
2 
3 my @list = (1..12);
4 my @shuffled = shuffle(@list);
5 print join(",",@list)," : original\n";
6 print join(",",@shuffled)," : shuffled\n";
7 
8 my $sum = sum(@list);
9 print "total is ", $sum, "\n";

Presenter Notes