Lesson 2. Control structures File IO - reading and writing Subroutines

Slides:



Advertisements
Similar presentations
1/12 Steven Leung Very Basic Perl Tricks A Few Ground Rules File I/O and Formatting Operators, Flow Control Statements Regular Expression Subroutines Hash.
Advertisements

● Perl reference
CSC 4630 Perl 1. Perl Practical Extraction and Support Language A glue language under UNIX Written by Larry Wall Claimed to be the most portable of scripting.
Computer Programming for Biologists Class 9 Dec 4 th, 2014 Karsten Hokamp
Introduction to Unix – CS 21 Lecture 11. Lecture Overview Shell Programming Variable Discussion Command line parameters Arithmetic Discussion Control.
Programming Perls* Objective: To introduce students to the perl language. –Perl is a language for getting your job done. –Making Easy Things Easy & Hard.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
CSET4100 – Fall 2009 Perl Introduction Scalar Data, Operators & Control Blocks Acknowledgements: Slides adapted from NYU Computer Science course on UNIX.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
CS311 – Today's class Perl – Practical Extraction Report Language. Assignment 2 discussion Lecture 071CS Operating Systems I.
Scalar Variables Start the file with: #! /usr/bin/perl –w No spaces or newlines before the the #! “#!” is sometimes called a “shebang”. It is a signal.
CS 330 Programming Languages 10 / 11 / 2007 Instructor: Michael Eckmann.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Prog.Perl Most operators have numeric and string version –remember Perl will convert variable.
Perl File I/O and Arrays. File I/O Perl allows to open a file to read, write, or append As well as pipe input or output to another program. —We get to.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
Shell Programming. Shell Scripts (1) u Basically, a shell script is a text file with Unix commands in it. u Shell scripts usually begin with a #! and.
1 Perl Perl basics Perl Elements Arrays and Hashes Control statements Operators OOP in Perl.
Control Structures. Important Semantic Difference In all of these loops we are going to discuss, the braces are ALWAYS REQUIRED. Even if your loop/block.
Introduction To Perl Susan Lukose. Introduction to Perl Practical Extraction and Report Language Easy to learn and use.
1 System Administration Introduction to Scripting, Perl Session 3 – Sat 10 Nov 2007 References:  chapter 1, The Unix Programming Environment, Kernighan.
CSC 352– Unix Programming, Spring 2015 March 2015 Shell Programming (Highlights only)
Meet Perl, Part 2 Flow of Control and I/O. Perl Statements Lots of different ways to write similar statements –Can make your code look more like natural.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
CS 330 Programming Languages 10 / 07 / 2008 Instructor: Michael Eckmann.
Introduction to Perl Yupu Liang cbio at MSKCC
Books. Perl Perl (Practical Extraction and Report Language) by Larry Wall Perl 1.0 was released to usenet's alt.comp.sources in 1987 Perl 5 was released.
Perl Language Yize Chen CS354. History Perl was designed by Larry Wall in 1987 as a text processing language Perl has revised several times and becomes.
Perl: Lecture 1 The language. What Perl is Merger of Unix tools – Very popular under UNIX – shell, sed, awk Programming language – C syntax Scripting.
Chapter 10: BASH Shell Scripting Fun with fi. In this chapter … Control structures File descriptors Variables.
Introduction to Unix – CS 21
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Computer Programming for Biologists Class 3 Nov 13 th, 2014 Karsten Hokamp
CS 105 Perl: Data Types Nathan Clement 15 May 2014.
©Colin Jamison 2004 Shell scripting in Linux Colin Jamison.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Topic 4:Subroutines CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 4, pages 56-72, Programming Perl 3rd edition pages 80-83,
A Few More Functions. One more quoting operator qw// Takes a space separated sequence of words, and returns a list of single-quoted words. –no interpolation.
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
Department of Electrical and Computer Engineering Introduction to Perl By Hector M Lugo-Cordero August 26, 2008.
Introduction to Perl. What is Perl Perl is an interpreted language. This means you run it through an interpreter, not a compiler. Similar to shell script.
Perl Variables: Array Web Programming1. Review: Perl Variables Scalar ► e.g. $var1 = “Mary”; $var2= 1; ► holds number, character, string Array ► e.g.
Intro to Object Oriented Perl Packages, Modules, Classes.
PERL By C. Shing ITEC Dept Radford University. Objectives Understand the history Understand constants and variables Understand operators Understand control.
Perl Scripting II Conditionals, Logical operators, Loops, and File handles Suzi Lewis Genome Informatics.
Perl for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
File Handle and conditional Lecture 2. File Handling The Files associated with Perl are often text files: e.g. text1.txt Files need to be “opened for.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
Dept. of Animal Breeding and Genetics Programming basics & introduction to PERL Mats Pettersson.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
Perl Subroutines User Input Perl on linux Forks and Pipes.
CSC 352– Unix Programming, Fall 2012
Perl Variables: Array Web Programming.
Subroutines Web Programming.
An Introduction to Perl
Basic Input/Output Web Programming.
Control Structures: for & while Loops
Context.
Pemrosesan Teks Herika Hayurani Sept 19, 2006
Programming Perls* Objective: To introduce students to the perl language. Perl is a language for getting your job done. Making Easy Things Easy & Hard.
Tonga Institute of Higher Education
CS 240 – Lecture 7 Boolean Operations, Increment and Decrement Operators, Constant Types, enum Types, Precedence.
CSC 352– Unix Programming, Fall, 2011
The Selection Structure
CSC 352– Unix Programming, Fall 2012
Subroutines.
CIS 136 Building Mobile Apps
INTRODUCTION to PERL PART 1.
Presentation transcript:

Lesson 2. Control structures File IO - reading and writing Subroutines Modules BioPerl

Comparisons and if statements The if statement: if (<condition>) { # do something } elsif (<another_condition>) { # do something else else { # do yet another thing a code block

comparators The result of a comparison is either true or false Boolean algebra Numeric values Compare numbers Is $a equal to $b? Larger? Smaller? ==, >, <, <=, >=, !=, <=> if ($a > $b) { print “$a is larger than $b\n”; } String values eq, ne, gt (greater than), lt (less than)

Boolean algebra AND OR NOT

Boolean values in Perl Perl has no boolean type Values that are “false” 0 (incl numerically assigned expressions that evaluate to zero) “” (the empty string) (NB. “ “ (a string containing a space) is true) undef (value of a variable that was declared but nothing assigned) The empty list The empty hash True values Everything else that is not true Convention: Assigning false: use 0. Assigning true: use 1.

Operator precedence * , / precedes +, - and, not precedes or 5 + (6 * 3) (5 + 6) * 3 and, not precedes or ( $x < 2 or $x > 5 and $y < 100) ) vs. ( ( $x < 2 or $x > 5 ) and $y < 100) See man perlop See also de Morgan's law: (! $x) and (! $y) = ! ( $x or $y ) (! $x) or (! $y) = ! ( $x and $y)

Boolean values in Perl Perl has no boolean type Values that are “false” 0 (incl numerically assigned expressions that evaluate to zero) “” (the empty string) (NB. “ “ (a string containing a space) is true) undef (value of a variable that was declared but nothing assigned) The empty list The empty hash True values Everything else that is not true Convention: Assigning false: use 0. Assigning true: use 1.

Operator precedence * , / precedes +, - and, not precedes or 5 + (6 * 3) (5 + 6) * 3 and, not precedes or ( $x < 2 or $x > 5 and $y < 100) ) vs. ( ( $x < 2 or $x > 5 ) and $y < 100) See man perlop See also de Morgan's law: (! $x) and (! $y) = ! ( $x or $y ) (! $x) or (! $y) = ! ( $x and $y)

File I/O - Reading Opening a file open(my $F, “<”, $filename); # “<”=reading # “>”=writing Reading from a file while (<$F>) { # reads into default var $_ chomp(); # removes newline my ($firstname, $lastname) = split /\t/; } Closing a file close($F);

File I/O - Writing Opening a file open(my $F, “>”, $filename); # “<”=reading # “>”=writing Writing to a file print $F “Hello World!\n”; Closing a file close($F);

File checks File check flags Check of the form if (-f $myfile) { -d directory -f plain file -l symbolic link -T text file Check of the form if (-f $myfile) { open ($F, “<”, $myfile) # etc.... See also

The open or die construct open (my $F, “<”, $myfile) or die “Can't open file $myfile”; The open() call returns true on success, false otherwise. The or operator evaluates the second operand only if the first operand is false (if the first operand is true, or will always be true!)

Reading directory listings The glob function my @files = glob “*.txt”; foreach my $f (@files) { print “$f\n” }

Subroutines Code that is duplicated in a script may be better in a subroutine Subroutines are called like other Perl functions Declaration and basic structure sub foo { my @params = @_; # do something... then... return $result; } Function call my $result = foo($param1, $param2);

Subroutine parameters The @_ array is an alias to the original parameters The original parameters will be changed if @_ is changed! Usually, @_ is assigned to more descriptive variables Once assigned, the variables are not aliases anymore Changing their values does not change the originals Examples sub foo { my $chromosome = shift @_; my $marker = shift; #operates on @_ by default my ($surface, $diameter) = @_;

CAVEAT! Subroutine parameters – multiple lists Function parameters such as: foo(@x, @y) Don't work, because in the subroutine: sub foo { my (@x, @y) = @_; All elements of @_ will be assigned to @x Use listrefs (or hashrefs) in this case foo(\@x, \@y) my ($xref, $yref) = @_;

Subroutine return values Subroutines that return values are sometimes called functions It is better for a function to return a value than to change the function parameters Return values can be scalars, lists, or hashes. Be careful with returning multiple lists or hashes. Need to return listrefs or hashrefs!

Modules Create re-usable code that scripts can load and use A module is a namespace Subroutines that are used from different scripts are better placed into modules Easier to maintain Documention Bug fixes

Modules Declaration package Foo; Notes about naming: Package names should be uppercase Often, package names are in CamelCase Mapping to filesystem: package Foo should be a file called Foo.pm package Foo::Bar is in Foo/Bar.pm Using modules use Foo::Bar;

@INC is like $PATH for modules How does Perl know where to look for modules? Perl looks in the current directory Perl looks in the order of directories given in @INC @INC is populated by Perl at startup Changing @INC List of paths given in the environment variable $PERL5LIB is pre-pended to @INC

Accessing other packages You are ALWAYS in a package in Perl The default package is called “main”. The “main” package identifier can be omitted. You can access all global variables declared in main by our $example=100; print $main::example.”\n”; You can access globals in other packages by print $MyOtherPackage::example; print $Foo::Bar::example;

Some standard modules Math File Getopt::Std Test Math::Complex Math::BigInt File File::Temp File::Basename File::Spec Getopt::Std Test

Bio::SeqIO Sequence input/output Usage use Bio::SeqIO; my $in = Bio::SeqIO->new(-format=>'fastq', - file=>$file); my $out = Bio::SeqIO->new(-format=>'fasta', - file=>”>$file.fasta”); while (my $s = $in->next_seq()) { $out->write_seq($s); }

Changing object properties use Bio::SeqIO; my $in = Bio::SeqIO->new(-format=>'fasta', - file=>$file); my $out = Bio::SeqIO->new(-format=>'fasta', - file=>”>$file.fasta”); while (my $s = $in->next_seq()) { my $id = $s->id(); my $new_id = $new_ids{$id}; $s->id($new_id); $out->write_seq($s); }