Introduction to Perl progammingPart I16/12/2010Ernesto LowyCRG Bioinformatics core
What is Perl?Perl is a programming language extensively used in bioinformaticsCreated by Larry Wall in 1987Provides powerful text processing facilities, facilitating easy manipulation of text filesPerl is an interpreted language (no compiling is needed)Perl is quite portable Programs can be written in many different ways (advantage?)Perl slogan is "There's more than one way to do it”Rapid prototyping (solve a problem with fewer lines of code than Java or C)
Installing PerlPerl comes by default on Linux and MacOSXOn windows you have to install it:http://strawberryperl.com/ (100% open source)http://www.activestate.com/ (commercial distribution-but free!)Latest version is Perl 5.12.0	To check if Perl is working and version	$perl –v
Perl resources	Web siteswww.perl.comhttp://perldoc.perl.org/https://www.socialtext.net/perl5/index.cgihttp://www.perlmonks.org/Books
 Learning Perl (good for begginers)
 Beginning Perl for Bioinformatics
 Programming Perl (Camel book)
 Perl cookbookEx1. First program…Open a terminalEnter which perlOpen your favourite text editor and enter#!/../path/to/perl –w	#prints Hello world in the screen	print “Hello world!\n”;4) Save it as hello.pl5) Execute it withperlhello.pl
1000 #integer1.25 #floating-point1.2e30 #1.2 times 10 to the 30th power-1-1.2Only important thing to remember is that you never insert commas or spaces into numbers in Perl. So in a Perl program you never will find:10 00010,000Perl basic data typesNumbers
A string is a collection of characters in either single or double quotes:“This is the CRG.”‘CRG is in Barcelona!’Difference between single and double quotes is:print “Hello!\nMy name is Ernesto\n”; #Interprete contentsWill display:>Hello!>My name is Ernestoprint ‘Hello!\nMy name is Ernesto\n’; #contents should be taken literallyWill display:>Hello!\nMy name is Ernesto\nPerl basic data typesStrings
Scalar variablesVariable is a name for a container that holds one or more values.Scalar variable (contains a single number or string):$a=1; $codon=“ATG”;$a_single_peptide=“GMLLKKKI”;(valid Perl identifiers are letter,words,underscore,digits)Important! Scalar variables cannot start with a digitImportant! Uppercase and Lowercase letters are distinct ($Maria and $maria)Example (Assignment operator):$codon=“ATG”;print “$codon codes for Methionine\n”;Will display:ATG codes for Methionine
Numerical operatorsPerl provides the typical operators. For example:5+3 #5 plus 3, or 53.1-1.2 #3.1 minus 1.2, or 1.94*4 # 4 times 4 = 166/2 # 6 divided by 2, or 3Using variables$a=1;$b=2;$c=$a+$b;print “$c\n”;Will print:3
Special numerical operators	$a++; #same than	$a=$a+1;$b--; #same than	$b=$b-1;$c +=10; #same than	$c=$c+10;
String manipulation	Concatenate strings with the dot operator	“ATG”.”TCA” # same as “ATGTCA”String repetition operator (x)	“ATC” x 3   # same as “ATCATCATC”Length() get the length of a string	$dna=“acgtggggtttttt”;	print “This sequence has “.length($dna).” nucleotides\n”;Will print:	This sequence has 10 nucleotidesconvert to upper case	$aa=uc($aa);convert to lower case	$aa=lc($aa);
Conditional statements(if/else)Determine a particular course of action in the program.Conditional statements make use of the comparison operators to compare numbers or strings. These operators always return true/false as a result of the comparison
Comparison operators(Numbers)Examples:35 == 35 # true35 != 35 # false35 != 32 # ????35 == 32+3 # ????
Comparison operators(Strings)Examples:‘hello’ eq ‘hello’ # true‘hello’ ne ‘bye’ # true‘35’ eq ‘35.0’ # ????
If/else statementAllows to control the execution of the programExample:$a=4;$b=10;If ($a>$b) {	print “$a is greater than $b\n”;} else {	print “$b is greater then $a\n”;}
elsif clauseTo check a number of conditional expressions, one after another to see which one is trueGame of rolling a dice. Player wins if it gets an even number$outcome=6; #enter here the result from rolling a diceif ($outcome==6)  {	print “Congrats! You win!\n”;} elsif ($outcome==4) {	print “Congrats! You win!\n”;} elsif ($outcome==2) {	print “Congrars! You win!\n”;} else {	print “Sorry, try again!\n”;}
Logical operators	Used to combine conditional expressions|| (OR)
Logical operatorsExample:$day=“Saturday”;if ($day eq “Saturday” || $day eq “Sunday”) {	print “Hooray! It’s weekend!\n”;}Will print:>Hooray! It’s weekend!
Logical operators&& (AND)Example:$hour=12;if ($hour >=9 && $hour <=18)  {	“You are supposed to be at work!\n”;}Will print:>You are supposed to be at work!
Boolean values	Perl does not have the Boolean data type. So how Perl knows if a given variable is true or false?If the value is a number then 0 means false; all other numbers mean trueExample:$a=15;$is_bigger=$a>10; # $is_bigger will be 1If ($is_bigger) {….}; # this block will be executed
Boolean values	If a certain value is a string. Then the empty string (‘’) means false; all other strings mean true$day=“”;#evaluates to false, so this block will not be executedif($day) { 	print $day contains a string}
Boolean valuesGet the opposite of a boolean value (! Operator)Example (A program that expects a filename from the user):print “Enter file name, please\n”;$file=<>;chomp($file); #remove \n from inputIf (!$file) { #if $file is false (empty string)	print “I need an input file to proceed\n”;}#try to process the file

Perl courseparti

  • 1.
    Introduction to PerlprogammingPart I16/12/2010Ernesto LowyCRG Bioinformatics core
  • 2.
    What is Perl?Perlis a programming language extensively used in bioinformaticsCreated by Larry Wall in 1987Provides powerful text processing facilities, facilitating easy manipulation of text filesPerl is an interpreted language (no compiling is needed)Perl is quite portable Programs can be written in many different ways (advantage?)Perl slogan is "There's more than one way to do it”Rapid prototyping (solve a problem with fewer lines of code than Java or C)
  • 3.
    Installing PerlPerl comesby default on Linux and MacOSXOn windows you have to install it:http://strawberryperl.com/ (100% open source)http://www.activestate.com/ (commercial distribution-but free!)Latest version is Perl 5.12.0 To check if Perl is working and version $perl –v
  • 4.
  • 5.
    Learning Perl(good for begginers)
  • 6.
    Beginning Perlfor Bioinformatics
  • 7.
    Programming Perl(Camel book)
  • 8.
    Perl cookbookEx1.First program…Open a terminalEnter which perlOpen your favourite text editor and enter#!/../path/to/perl –w #prints Hello world in the screen print “Hello world!\n”;4) Save it as hello.pl5) Execute it withperlhello.pl
  • 9.
    1000 #integer1.25 #floating-point1.2e30#1.2 times 10 to the 30th power-1-1.2Only important thing to remember is that you never insert commas or spaces into numbers in Perl. So in a Perl program you never will find:10 00010,000Perl basic data typesNumbers
  • 10.
    A string isa collection of characters in either single or double quotes:“This is the CRG.”‘CRG is in Barcelona!’Difference between single and double quotes is:print “Hello!\nMy name is Ernesto\n”; #Interprete contentsWill display:>Hello!>My name is Ernestoprint ‘Hello!\nMy name is Ernesto\n’; #contents should be taken literallyWill display:>Hello!\nMy name is Ernesto\nPerl basic data typesStrings
  • 11.
    Scalar variablesVariable isa name for a container that holds one or more values.Scalar variable (contains a single number or string):$a=1; $codon=“ATG”;$a_single_peptide=“GMLLKKKI”;(valid Perl identifiers are letter,words,underscore,digits)Important! Scalar variables cannot start with a digitImportant! Uppercase and Lowercase letters are distinct ($Maria and $maria)Example (Assignment operator):$codon=“ATG”;print “$codon codes for Methionine\n”;Will display:ATG codes for Methionine
  • 12.
    Numerical operatorsPerl providesthe typical operators. For example:5+3 #5 plus 3, or 53.1-1.2 #3.1 minus 1.2, or 1.94*4 # 4 times 4 = 166/2 # 6 divided by 2, or 3Using variables$a=1;$b=2;$c=$a+$b;print “$c\n”;Will print:3
  • 13.
    Special numerical operators $a++;#same than $a=$a+1;$b--; #same than $b=$b-1;$c +=10; #same than $c=$c+10;
  • 14.
    String manipulation Concatenate stringswith the dot operator “ATG”.”TCA” # same as “ATGTCA”String repetition operator (x) “ATC” x 3 # same as “ATCATCATC”Length() get the length of a string $dna=“acgtggggtttttt”; print “This sequence has “.length($dna).” nucleotides\n”;Will print: This sequence has 10 nucleotidesconvert to upper case $aa=uc($aa);convert to lower case $aa=lc($aa);
  • 15.
    Conditional statements(if/else)Determine aparticular course of action in the program.Conditional statements make use of the comparison operators to compare numbers or strings. These operators always return true/false as a result of the comparison
  • 16.
    Comparison operators(Numbers)Examples:35 ==35 # true35 != 35 # false35 != 32 # ????35 == 32+3 # ????
  • 17.
    Comparison operators(Strings)Examples:‘hello’ eq‘hello’ # true‘hello’ ne ‘bye’ # true‘35’ eq ‘35.0’ # ????
  • 18.
    If/else statementAllows tocontrol the execution of the programExample:$a=4;$b=10;If ($a>$b) { print “$a is greater than $b\n”;} else { print “$b is greater then $a\n”;}
  • 19.
    elsif clauseTo checka number of conditional expressions, one after another to see which one is trueGame of rolling a dice. Player wins if it gets an even number$outcome=6; #enter here the result from rolling a diceif ($outcome==6) { print “Congrats! You win!\n”;} elsif ($outcome==4) { print “Congrats! You win!\n”;} elsif ($outcome==2) { print “Congrars! You win!\n”;} else { print “Sorry, try again!\n”;}
  • 20.
    Logical operators Used tocombine conditional expressions|| (OR)
  • 21.
    Logical operatorsExample:$day=“Saturday”;if ($dayeq “Saturday” || $day eq “Sunday”) { print “Hooray! It’s weekend!\n”;}Will print:>Hooray! It’s weekend!
  • 22.
    Logical operators&& (AND)Example:$hour=12;if($hour >=9 && $hour <=18) { “You are supposed to be at work!\n”;}Will print:>You are supposed to be at work!
  • 23.
    Boolean values Perl doesnot have the Boolean data type. So how Perl knows if a given variable is true or false?If the value is a number then 0 means false; all other numbers mean trueExample:$a=15;$is_bigger=$a>10; # $is_bigger will be 1If ($is_bigger) {….}; # this block will be executed
  • 24.
    Boolean values If acertain value is a string. Then the empty string (‘’) means false; all other strings mean true$day=“”;#evaluates to false, so this block will not be executedif($day) { print $day contains a string}
  • 25.
    Boolean valuesGet theopposite of a boolean value (! Operator)Example (A program that expects a filename from the user):print “Enter file name, please\n”;$file=<>;chomp($file); #remove \n from inputIf (!$file) { #if $file is false (empty string) print “I need an input file to proceed\n”;}#try to process the file
  • 26.
    die() functionRaises anexception, which means that throws an error message and stops the execution of the program.So previous example revisited:print “Enter file name, please\n”;$file=<>;chomp($file); #remove \n from inputif (!$file) { #if $file is false (empty string)die(“I need an input file to proceed\n”);}#process the file only if $file is defined
  • 27.
    Ex 2. Usingconditional expressions TODO: Write a program to get an exam score from the keyboard and prints out a message to the student.Hint: To read input from keyboard enter in your programprint "Enter the score of a student: ";$score = <>;
  • 28.
    Solution#! /usr/bin/perlprint "Enterthe score of a student: ";$score = <>; if($score>=90) { print "Excellent Performance!\n";} elsif ($score>=70 && $score<90) { print "Good Performance!\n”;} elsif ($score>=50 && $score<70) { print "Uuff! That was close!\n”;} else { print "Sorry, try harder!\n";}

Editor's Notes

  • #3 -Larry wall is a linguist-what does the Perl interpreter do? It compiles the program (source code) internally intobytecode and then executes it immediately. Perl is commonly known as an interpreted language, but this is not strictly true. Since the interpreter actually does convert the program into byte code before executing it, it is sometimes called an interpreter/compiler , if anything at all. [ 1 ] Although the compiled form is not stored as a file, release 5.005 of Perl includes a working version of a standalone Perl compiler.[1] So do you call something a Perl &quot;script&quot; or a Perl &quot;program&quot;? Typically, the word &quot;program&quot; is used to describe something that needs to be compiled into assembler or byte code before executing, as in the C language, and the word &quot;script&quot; is used to describe something that runs through an interpreter, as in the Bourne shell. For Perl, you can use either phrase and not worry about offending anyone.What does all this brouhaha mean for you? When you write a Perl program, you can just give it a correct #! line at the top of the script, make it executable with chmod +x , and run it. For 95% of Perl programmers in this world, that&apos;s all you&apos;ll care about.
  • #5 http://perldoc.perl.org/ (official documentation)https://www.socialtext.net/perl5/index.cgi (Perl wiki)
  • #6 -#! (hash-bang or shebang) tells the shell where to look for perl-The print built-in function is one of the most frequently used parts of Perl. You use it to display things on the screen or to send information to a file.-Perl program consists of statements, each of which ends with a semicolon.-”.pl” extension is optional but is commonly used-”-w” switches on warnings: is not required but it is advisable
  • #9 -Perl identifier is what follows the dollar sign-Choosing Good Variable Names. You should generally select variable names that mean something regarding the purpose of the variable. For example, $r is probably not very descriptive but $line_length is.