Docsity

Perl Primer - Computer Structural Bioinformatics - Lecture Notes | ECS 129, Exams of Computer Science

Toggle sidebar
bg1
1
Perl Primer
Patrice Koehl
Department of Computer Sciences, University of California, Davis.
Acknowledgments:
This primer is mostly a compilation of information found in three books that I highly
recommend:
- “Beginning Perl” by Simon Cozens, which can be found online at
http://www.perl.org/books/beginning-perl/. This is a free book, and a great introduction
to Perl programming.
- “Perl programming for Biologists”, by D. Curtis Jamison (Wiley-Liss publisher). This is
a small book with many examples/problem sets related to biology. I like the way it is
structured.
- “Beginning Perl for Bioinformatics”, by James Tisdall (O’Reilly publisher)
Introduction
1. Why Perl?
“Perl” is an interpreted computer language. The name “Perl” is not really an acronym, but it is
usually believed to mean “Practical Extraction and Report Language”. More importantly, Perl is
a language for doing what you want to do.
It is important to understand that there is always more than one way to solve a problem. In
programming, Perl focuses on getting the job done. One Perl program may be faster than
another, or more concise, or easier to understand, but it both do the same thing, there won’t be a
judgment that defines which one is “better”. This also means that you do not need to know every
detail about the language to do what you want with it.
Perl has strength that makes it an ideal language to learn and use:
- It is completely free, and available on all operating system
- It is very easy to learn
- Perl was designed to be easy for humans to write, rather than easy for computer to
understand. Perl syntax is more like English than other programming languages
- Perl is very portable. Perl programs can be run on any computers, as long as Perl is
installed on it.
- Perl “talks” texts. It works with words and sentences, instead of characters. Files are
series of lines, instead of individual bytes.
- Perl is a “high-level” language: you do not have to worry about the computer’s operation
(such as allocation and de-allocation of memory, 
).
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c

Partial preview of the text

Download Perl Primer - Computer Structural Bioinformatics - Lecture Notes | ECS 129 and more Exams Computer Science in PDF only on Docsity!

Perl Primer

Patrice Koehl

Department of Computer Sciences, University of California, Davis. Acknowledgments: This primer is mostly a compilation of information found in three books that I highly recommend:

  • “Beginning Perl” by Simon Cozens, which can be found online at http://www.perl.org/books/beginning-perl/. This is a free book, and a great introduction to Perl programming.
  • “Perl programming for Biologists”, by D. Curtis Jamison (Wiley-Liss publisher). This is a small book with many examples/problem sets related to biology. I like the way it is structured.
  • “Beginning Perl for Bioinformatics”, by James Tisdall (O’Reilly publisher)

Introduction

1. Why Perl? “Perl” is an interpreted computer language. The name “Perl” is not really an acronym, but it is usually believed to mean “Practical Extraction and Report Language”. More importantly, Perl is a language for doing what you want to do. It is important to understand that there is always more than one way to solve a problem. In programming, Perl focuses on getting the job done. One Perl program may be faster than another, or more concise, or easier to understand, but it both do the same thing, there won’t be a judgment that defines which one is “better”. This also means that you do not need to know every detail about the language to do what you want with it. Perl has strength that makes it an ideal language to learn and use:

  • It is completely free, and available on all operating system
  • It is very easy to learn
  • Perl was designed to be easy for humans to write, rather than easy for computer to understand. Perl syntax is more like English than other programming languages
  • Perl is very portable. Perl programs can be run on any computers, as long as Perl is installed on it.
  • Perl “talks” texts. It works with words and sentences, instead of characters. Files are series of lines, instead of individual bytes.
  • Perl is a “high-level” language: you do not have to worry about the computer’s operation (such as allocation and de-allocation of memory, 
).

It is only fair to mention that these strengths can also translate into weaknesses:

  • Perl takes care for you of all “low-level” operations: this may not always lead to efficient code
  • Perl is interpreted, and loses the efficiency of compiled languages.
  • Perl users then to write programs for small, specific jobs. These programs are usually for the programmer’s eye only, and as such are often incomprehensible to everyone but the original programmer. In that respect, I can only emphasize the need for clarity, as well as for useful comments in your source files!
  • Perl was designed to be easy for humans. As a consequence, it is relatively lenient on the style you use. This can lead to bad programming habits. As an analogy, think of what would happen to your English writing style if nobody had ever cared about how you write as long as they understand what you have written. To avoid this, the key is to develop first a method to solve your problem that is independent of Perl or any other language, and then to adapt this method to Perl. 2. What is Perl used for? Perl is widely used for extracting data from one source and translating it to another format. This includes manipulating databases, formatting and reformatting text files, search-and-replace operations, organizing and manipulating experimental data. Perl is used to manage the data from the Human Genome Project. Perl is a very useful programming language for system administrators, as it allows then to automate administration tasks, tidying up the systems, process logs, produce reports on system usage and watch for security usage. The most popular use of Perl however is for CGI programming, that is for dynamically generating web pages. 3. How do I get Perl? Perl has been ported to many platform, and will certainly run on the standard operating systems such as UNIX, Linux, Solaris, FreeBSD, all flavors of Windows, and Apple MacOS. Where to get Perl:
  • You can get the source to the latest stable release of Perl from http://www.perl.com/CPAN-local/src/README.html
  • Binary distributions for some ports are available at http://www.perl.com/CPAN- local/ports/index.html
  • You can get binary packages of Perl for Linux, Solaris, Mac OS and Windows from ActiveState at http://www.activestate.com/ActivePerl (free for download)

Using Perl in command line If you are mainly using your computer in a graphical environment like Windows or X, you may not be familiar with using the command line interface, or “shell”. The “shell” is the program that gets input from you through the keyboard. The “shell prompt” or just “prompt” refers to the text that prompts you to enter a program name and more generally, to working with the shell instead of using a graphical interface. To get to a prompt in Windows, choose “run” in the start menu, and type cmd in the “run” window. Under Linux/Unix/Mac Os X, look for a program called terminal, konsole, xterm or kterm. In both cases, you will then be faced with a usually black screen with a little bit of text that may look like: $ % C:>

bash$ In this primer, I will use a prompt that looks like: ! I will show the test that you would type in bold and the text the computer generates in italic: ! perl hello.plx Hello World!

5. Your first Perl program Traditionally, the first program anyone writes in a new language is called “Hello World!”, where you make the program prints that statement. Perl allows us to do so using the print statement. The simplest form of the print statement takes a single argument and writes it to the standard output, i.e. the command window you have open. So your program consists of the single statement: print “Hello World!\n”; There are two ways to use Perl:

  • you can use a single command line, in which you put the Perl statement between quote:

! perl - e 'print "Hello World!\n";'

  • you create a file that contains all your statements, and execute it: ! perl hello.plx The file hello.plx contains: The different elements of a Perl script:
  • The first line (not required) : #! /usr/bin/perl indicates that the file contains a source code that should be executed by Perl. This is not a Perl command per se: it only signals to the shell how it should interpret the file.
  • Directives: the statement use warnings tells the interpreter to output “meaningful” warnings if there are syntax errors in the file
  • Documenting the program : any line (except the first) starting with a sharp (#) is treated as a command line and ignored. This allows you to provide comments on what your program is doing: this is extremely useful, so use it! More generally, a line in a Perl script may contain some Perl code, and be followed by a comment. This means that we can document the program “inline”.
  • Keywords: Instructions that Perl recognizes and understands. The word print in the program above is one example. There are two types of keywords:
  • functions (such as the print keyword); these are the verbs of the programming language and they tell perl what to do.
  • Control keywords , such as if and else. It is a good idea to respect keywords, and not use them as names in your programs, even though Perl tolerates this.
  • Statements: Statements are the sentences of the program. Instead of a full stop, a statement in Perl usually ends with a semicolon, as in the program above. There are times when you can get away without using the semicolon (when it is absolutely clear to Perl that the statement is finished, such as for example the last statement in a program), but I strongly advise against this. It is good practice to always end a statement with a semicolon. Statements can be grouped together into a block (just like a paragraph in a text), by surrounding them with braces: {
}: #! /usr/bin/perl use warnings; # Set warning flags to detect errors

print “Hello World!\n”;

Chapter 1: Scalar Variables and Data Types

1. Perl Variables A variable is a name reference to a memory location. Variables provide an easy handle to keep track of data stored in memory. Most often, we do not know the exact value of what is in a particular memory location, rather we know the type of data that is stored there. Perl has three main types of variables:

  • Scalar variables hold the basic building blocks of data: numbers, and characters.
  • Array variables hold lists referenced by numbers (indices)
  • Hash variables hold lists references by labels. The three types are distinguished by the first character in the variable name: ‘$’, ‘@’, and ‘%’ for scalar, array and hash variables, respectively. Following the type symbol, the name can be practically any combination of characters and of arbitrary length. Creating a variable is as simple as making up a variable name and assigning a value to it. There are a few rules regarding variable names that you need to be aware of:
  • The second character of a name should be either a letter (A to Z or a to z), a digit ( 0 to
  1. or an underscore (_). Most character names that consist of a single character have a predefined significance, and should therefore be avoided.
  • If you have a digit in the second position, the name can only contain more digits: $100 is valid, but $10a is not.
  • Spaces are one type of characters that are not allowed: use underscore instead.
  • Variables are case sensitive: this means that $dna refers to a different location in memory than $DNA. Assigning a value to a variable is easy: all you have to do is write an equation, with the variable name on the left, an = sign, and the value on the left. The = sign is called the assignment operator. 2. Special variables Perl has many predefined special variables that contains default values designed to make life easier for programmers. Since Perl variables can be reassigned, there is a danger that you modify one of these variables accidentally. These variables are usually a combination of obscure characters, and if you give meaningful names to your variables, you should not have this problem. Here is a list of the most common ones:

Variable Function $_ Default input $, Output field separator @ARGV Array with the command line arguments

3. Scalar variables Perl has two types of scalar values: numbers and strings. Both types ca be assigned to a scalar variables. 3. 1 Numbers Numbers are specified in any of the common integer or floating point format: Numbers can also be represented using octal or hexadecimal notations, but we will not need that. Table of the most common number operators in perl: Operator Meaning = Assign

  • Add
  • Substract
  • Multiply / Divide ** Exponentiation % Modulus cos() Cosine sin() Sine sqrt() Square root += Assign add
  • = Assign substract *= Assign multiply /= Assign divide ++ Autoincrement
    • Autodecrement Perl allows us to use all standard arithmetics operators on numbers, plus a few others. The mathematical operations are performed in the standard order of precedence: power comes first, then multiplication has a higher precedence than addition and substraction: 2+3*4 is equal to 14, $x = 1; # Integer $y = 5.14; # Floating point $z = 3. 25 E- 7 # Scientific notation

The autoincrement and autodecrement operators: There are two more operators on number that are useful, ++ and - -. They add and substract one from the variable, but their precedence is a little strange, and depends on where they are placed with respect to the variable. Try and run the following code: You should see the following output: ! perl hello.plx The original variables are: a = 10 and b = 6 After incrementing : a = 11 and b = 10 Now we have : a = 12 and b = 24 Finally, we have: a = 27 and b = 23 How does it work? Let us go through the program step by step:

  • First, we set up the variables $a and $b: $a = 10 ; $b = 6 ; print “The original variables are: a = ”,$a, “ and b = ”, $b,”\n”;
  • In the following line, the assignment happens before the increment. $b is set to the current value of $a, 10, and then $a is autoincremented, becoming 11: $b = $a++; print “After incrementing : a = ”,$a, “ and b = ”, $b,”\n”; #! /usr/bin/perl

Program: testop.plx

use warnings; $a = 10; $b = 6; print “The original variables are: a = ”,$a, “ and b = ”, $b,”\n”; $b = $a++; print “After incrementing : a = ”,$a, “ and b = ”, $b,”\n”; $b = ++$a*2; print “Now we have : a = ”,$a, “ and b = ”, $b,”\n”; $a=--$b+4; print “Finally, we have: a = ”,$a, “ and b = ”, $b,”\n”;

  • In the next line, the incrementing takes place first. $a is now 12, and $b is set to 2* this, i.e. 24 $b = ++$a*2; print “Now we have : a = ”,$a, “ and b = ”, $b,”\n”;
  • Finally, $b is decremented first, and becomes 23. $a is set to $b plus 4, which is 27. $a=--$b+ 4 ; print “Finally, we have: a = ”,$a, “ and b = ”, $b,”\n”; 3. 2 Strings A string is a group of characters attached together, enclosed by quotation marks. For now, we will only consider double quotes. Just like with numbers, many operations can be performed on strings: the most common ones are listed in the table below. String operator Meaning . (dot) Concatenation reverse Reverse the characters in the string. =~ Binding m/Pattern/ Matching operator s/Pattern1/Pattern2/ Substitution operator tr/Pattern1/Pattern2/ Translate operator Concatenating strings: The dot operator, when placed between two strings, creates a single string that concatenates the two original strings. In the following program: The variable $DNA contains the string “ATTGCGGCCT”. Note that the concatenation operator can be attached to an assignment: $DNA.=”G”; would add a “G” at the end of the string contained in $DNA. #! /usr/bin/perl use warnings $DNA1=”ATTGC”; $DNA2=”GGCCT”; $DNA=$DNA1.$DNA2;

a) Substitute The substitute operator s is useful for performing large-scale search and replacement. For example, we might want to replace a DNA sequence to an RNA sequence. The code would look like this: This codes tells Perl to take the string stored in $RNA and replace every T with a U. The g switch tells the operator that it needs to do it globally, .e. through the whole string. Figure 1: The substitute operator There are two other possible switches for the substitute operator:

  • the i switch indicates that the operator is case insensitive (in the example above, both T and t would be replaced with U if i is used)
  • the e switch indicates that the replacement PATTERN should be treated as Perl code; this is useful if the replacement pattern is stored in a variable: Note that it does not matter in which order you put the switches.

$RNA=$DNA;

$RNA=~s/T/U/g; $newbase=”U”; $RNA =~ s/T/$newbase/eg;

b) Translate The substitute operator is powerful but it does have some pitfalls. Think about the problem of substituting all As to Ts and all Ts to As in a DNA sequence. Naively, you would use the substitute operator twice: But
If the initial sequence is “ATAT”, the first substitute command would yield $NewDNA=”TTTT”, and after the second substitute command, $NewDNA contains “AAAA”, and not “TATA” as expected. What we really want to do, is perform the two substitute commands simultaneously: this is exactly what the operator tr does! Figure 2 illustrates how it works. Figure 2: The tr statement Note that we did not use the global switch: tr always work globally. There are two main switches for tr:

  • The [c]omplement switch inverses the search list, interpreting the list as containing every possible character except those listes in the search list. For example, tr /ATGC/ /c; replaces every character that is not a A, T, G or C with a space.
  • The [d]elete switch causes any matches to be removed completely: tr /ATGC//cd; removes every character that is not a A, T, G or C. The tr operator returns a scalar value stating how many replacements were made. We can make use of this to count symbols if we make the replacement list the same as the search list. For example, to count the number of purines in a DNA sequence, we can use: Because this is a common task, Perl provides a shortcut: leaving out the replacement list causes the search list to be replicated as the replacement list. So we could have written: $NewDNA=$DNA; $NewDNA=~ s/A/T/g; $NewDNA=~ s/T/A/g; $Npurine = ($DNA=~tr/AG/AG/); $Npurine = ($DNA=~tr/AG//);

Note that we need to put a backslash in front of the dollar sign, otherwise Perl will interpret $7 as a variable. Finally, if the string we want to print contains a backslash (/), we need to hide it from Perl by putting a backslash in front! To print \C, we would use:

5. Introducing STDIN Often when we write a Perl script, we need to be able to ask the user for additional data when (s)he runs the program. The way to do this is with the construct . I will explain this in more details when we look at files. Basically, reads a line from the file called standard input. Usually, the standard input is not really a file, but the user’s keyboard. Similarly, the print function writes by default to the file called standard output, which is usually the user’s screen. In order the user for a line of text (say a DNA sequence), we write something like: Note that the DNA sequence read in will have one extra character, corresponding th the carriage return. To remove it, we can use the command: print “\C\n”; print “Enter your DNA sequence : “; $DNA = ; chomp($DNA);

Exercises:

  1. Without the aid of a computer, work out the order in which each of the following expressions would be computed and their value. i. 2 + 6/ 4 - 35+ 1 ii. 17 + - 33/ 2 iii. 26+34 iv. 22*2+ 2 Verify your answer by writing a small Perl program that implements these expressions.
  2. Without the aid of a computer, work out these successive expressions and give the values of $a, $b, $c and $d upon completion. Then check your answer using a Perl script:
  3. Write a Perl program that: i. Reads a DNA sequence from standard input ii. Writes it on standard output all in lower case iii. Writes in on standard output with the purines in upper case and the pyrimidines in lower case iv. Writes the sequence in reverse order
  4. Write a Perl program that: i. Reads a DNA sequence from standard input ii. Counts the number of purines and pyrimidines iii. Counts the number of A, T, G and C.
  5. Write a Perl program that: i. Reads a DNA sequence from standard input (5’ !3’) ii. Writes the corresponding RNA sequence iii. Writes the sequence of the complementary strand (5’!3’)
  6. Write a Perl program that: i. Reads a DNA sequence from standard input (5’ !3’) ii. Remove all Guanines iii. Replaces all Thymines with Uracil iv. Count number of remaining nucleotides v. Writes the resulting sequence on standard output $a=4; $b=9; $c=5; $d=++$a2+$b++3; $c+=--$d/3; $b%=$a; $a=--$b;

Chapter 2: Lists, Arrays and Hashes

1. Higher order organization of data

In the previous chapter, we have seen the concept of scalar variables that define memory space in which we store a scalar, i.e. single numbers or strings. Scalar values however are usually insufficient to deal with current data. Imagine writing a program that analyzes the whole human genome. Since it contains approx. 30 , 000 genes, we would have to create 30, 000 variables to store their sequences! Initializing these variables would already be a daunting task, but imagine that you wanted to count the number of times the codon ATG appears in each gene, you would have to write one line of code for each gene, hence 30, 000 lines, changing only the variable name for the gene! Fortunately, Perl thinks that laziness is a virtue, and would never tolerate that you have to write 30, 000 lines of code. Two special types of variables exist to help managing long lists of items, namely arrays and hashes. These variables store lists of data, and each piece of data is referred to as an element. In this chapter, we will look in details at what are lists, and how they are stored and manipulated within arrays and hashes.

2. Lists

We are all familiar with lists: think about a shopping list, a soccer team roster, all integers between 1 and 10, genes in the human genomes,
A list can be ordered (increasing or decreasing values for numbers, lexicographic order for strings), or unordered.

2. 1 Lists in Perl How do we represent a list within Perl? By definition, a Perl list is a set of comma-separated values enclosed in parentheses. Examples: - (1,2, 3 ,4, 5 ,6, 7 ,8, 9 ,10) is the list of integers between 1 and 10 - (‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’) is the list of days in the week. We have used lists in chapter 1 , without knowing it! Remember when we were using the command: print “Finally, we have: a = ”,$a, “ and b = ”, $b,”\n”; We were in fact asking the command “print” to display on the screen the list of strings “Finally, we have: a=”, “$a”, “ and b= “, “$b”, and “\n”! Because Perl is lenient on grammar rule, it did

not complain about the fact that we forgot to put the elements of the list between parentheses. The correct syntax for this command should have been: print ( “Finally, we have: a = ”,$a, “ and b = ”, $b,”\n”); Let us look now at a list of numbers: (1, 4 ,6). If we print it using: We would get: 146! Perl does not automatically put spaces between lists of elements for us, nor does it put a new line on the end. If we want separators when we print them, we need to put them ourselves. Note that lists in Perl can be mixed: you can include strings, numbers, scalar variables and even lists in a single list!

2. 2 Accessing list values We have seen how to build a list. Another thing that is useful is to be able to access a specific element or set of elements from a list. The way to do this is to place the number of the element we want is square brackets after the list. Let us look at an example: Which day do you think will be printed? If you try this program, you will get: ! Wednesday Why didn’t we get “Tuesday”, the second element of the list? This is because Perl starts counting from 0 and not 1!! This is something important to remember. You should also notice that we use two sets of parentheses after the command “print”: the inner parentheses define the list of days of the week. When we choose element 2 of this list, we have generated an element, which we pair with “\n” to form a second list. The element you want does not have to be literal: it can be a variable as well. As an exercise, write a small program that reads in a number between 1 and 7, and outputs the corresponding day of the week. The answer is on the next page. print ( 1 ,4, 6 ); use warnings;

print element 2 of the list of days of the week:

print ((‘Monday’,’Tuesday’,’Wednesday’,’Thursday’,’Friday’,’Saturday’,’Sunday’)[ 2 ],”\n”);