1 Perl Syntax: control structures Learning Perl, Schwartz.

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

A Guide to Unix Using Linux Fourth Edition
● Perl reference
Week Four Agenda Announcements Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems.
Input from STDIN STDIN, standard input, comes from the keyboard. STDIN can also be used with file re-direction from the command line. For instance, if.
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.
Scripting Languages Chapter 6 I/O Basics. Input from STDIN We’ve been doing so with $line = chomp($line); Same as chomp($line= ); line input op gives.
Perl Lecture #1 Scripting Languages Fall Perl Practical Extraction and Report Language -created by Larry Wall -- mid – 1980’s –needed a quick language.
Engineering H192 - Computer Programming The Ohio State University Gateway Engineering Education Coalition Lect 6P. 1Winter Quarter I/O in C Lecture 6.
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.
Guide To UNIX Using Linux Third Edition
Regular Expressions Regular Expression (or pattern) in Perl – is a template that either matches or doesn’t match a given string. if( $str =~ /hello/){
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.
Chapter 4: UNIX File Processing Input and Output.
1 Course Lectures Available on line:
Programming Perl in UNIX Course Number : CIT 370 Week 4 Prof. Daniel Chen.
Introduction to Perl Practical Extraction and Report Language or Pathologically Eclectic Rubbish Lister or …
Introduction to Perl & BioPerl Dr G. P. S. Raghava Bioinformatics Centre Bioinformatics Centre IMTECH, Chandigarh Web:
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
Chap 3 – PHP Quick Start COMP RL Professor Mattos.
CIS 218 Advanced UNIX1 CIS 218 – Advanced UNIX (g)awk.
More on Input Output Input Stream : A sequence of characters from an input device (like the keyboard) to the computer (the program running). Output Stream.
Introduction to Bash Programming Ellen Zhang. Previous three classes What have we learnt so far ?
Linux+ Guide to Linux Certification, Third Edition
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.
Week Four Agenda Announcements Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
Sed, awk, & perl CS 2204 Class meeting 13 *Notes by Mir Farooq Ali and other members of the CS faculty at Virginia Tech. Copyright 2003.
Lecture 4 Looping. Building on the foundation Now that we know a little about  cout  cin  math operators  boolean operators  making decisions using.
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.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
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
5 1 Data Files CGI/Perl Programming By Diane Zak.
(A Very Short) Introduction to Shell Scripts CSCI N321 – System and Network Administration Copyright © 2000, 2003 by Scott Orr and the Trustees of Indiana.
Iteration While / until/ for loop. While/ Do-while loops Iteration continues until condition is false: 3 important points to remember: 1.Initialise condition.
CS 330 Programming Languages 10 / 02 / 2007 Instructor: Michael Eckmann.
I/O Redirection & Regular Expressions CS 2204 Class meeting 4 *Notes by Doug Bowman and other members of the CS faculty at Virginia Tech. Copyright
LIN Unix Lecture 5 Unix Shell Scripts. LIN Command Coordination ; && || command1 ; command2 Interpretation: Do command 1. Then do command.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Copyright © 2003 ProsoftTraining. All rights reserved. Perl Fundamentals.
Random Bits of Perl None of this stuff is worthy of it’s own lecture, but it’s all a bunch of things you should learn to use Perl well.
Introduction to Perl October 4, 2004 Class Meeting 7 * Notes on Perl by Lenwood Heath, Virginia Tech © 2004.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
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.
Computer Programming for Biologists Class 4 Nov 14 th, 2014 Karsten Hokamp
Linux+ Guide to Linux Certification, Second Edition
CSC 4630 Meeting 17 March 21, Exam/Quiz Schedule Due to ice, travel, research and other commitments that we all have: –Quiz 2, scheduled for Monday.
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.
Finding substrings my $sequence = "gatgcaggctcgctagcggct"; #Does this string contain a startcodon? if ($sequence =~ m/atg/) { print "Yes"; } else { print.
Introduction to Programming the WWW I CMSC Winter 2003 Lecture 17.
CS 360 Internet Programming. Objectives for this class period Web programming is important Administrative organization of the course Introduction to first.
CSC 4630 Perl 3 adapted from R. E. Beck. Problem But we worked on it first: Input: Read from a text file named in a command line argument Output: List.
CS 330 Programming Languages 09 / 30 / 2008 Instructor: Michael Eckmann.
Perl Subroutines User Input Perl on linux Forks and Pipes.
Linux Administration Working with the BASH Shell.
Week Four Agenda Announcements Link of the week Review week three lab assignment This week’s expected outcomes Next lab assignment Break-out problems.
Input from STDIN STDIN, standard input, comes from the keyboard.
Control Flow Constructs: Conditional Logic
Introduction to Bioinformatic Computation. Lecture #
Pemrosesan Teks Herika Hayurani Sept 19, 2006
Introduction to Bioinformatic Computation. Lecture #
Presentation transcript:

1 Perl Syntax: control structures Learning Perl, Schwartz

2 FYI

3 Outline Control structures –if, for, while, foreach File Handles and Streams Regular Expressions -- a start

4 Expression Evaluation for Control Structures if (CONDITION) { ….. lines in this block will be executed } CONDITIONS evaluate as true: 1)any string except "" and "0" 2)Any number except 0 3)Any reference is true All undefined values are false

5 Control Structures Provides the capability to make decisions based on results if( something is true) do this else do something else

6 if Control Structure if (condition) { execute block } elsif (condition) { } elsif (condition) { } : else { }

7 if Control Structure if ( $i > 60) { print "Length of line is ".length($line)." \n"; } if ($sequence eq 'ATG') { $start_index = $x; $j =$j + 1; } else { print "Start codon not found."; } Note that in C -- you can have a single line of execution following an "if" if(j > 60) printf ("print statement here \n",j);

8 Examples if ($sequence eq 'ATG') { $start_index = $x; $j = $j + 1; } elsif ($sequence eq 'ATT') { $stop_location = $y; } else { print "Start/stop codons not found."; }

9 Block/Braces Conventions if ($i == 5) { # this is how most of the world writes code print "Hello world.\n"; } else { $x=0; } ####################################### if ($i == 5) # this is an alternative sometimes used { # either way is purely a stylistic choice print "Hello world.\n"; } else { $x=0; }

10 Iterative/Looping Control Structures while (condition) { #block is repeatedly ….block# executed as long as }# condition is TRUE while ($count < 300) { $count++; # same as $count = $count + 1; $number = ; &calc_sales($number); }

11 Strange Example #!/usr/bin/perl ## hellow world #comments $i = "ATG"; $j = "TTTG"; if($i == $k) { print "Prof braun was wrong\n"; }

12 for loop for( initialization; condition; execute) { block } 1)Initialization statement is executed, first, only once 2)CONDITION is evaluated, if true BLOCK is executed 3)EXECUTE is performed 4)Go to 2)

13 for loop for( initialization; expression; execute) { block } Equivalent to while loop initialization; while (expression){ block execute }

14 for loop examples (nearly identical to C structure) for ($i=0; $i<4; $i = $i+1) { print "Counting $i \n"; } print "Out of loop: $i \n"; Counting 0 Counting 1 Counting 2 Counting 3 Out of loop: 4

15 for loop examples for (my $i=0; $i<4; $i = $i+1) { print "Counting $i \n"; } print "Out of loop: $i \n"; Counting 0 Counting 1 Counting 2 Counting 3 Out of loop: for( ; $i<10 ; ) { # expressions are optional – none == infinite loop }

16 foreach Really no equivalent in C. foreach SCALAR ( ARRAY) { = (A,T,C); foreach $nucleotide { print $nucleotide."\n"; } A T C

17 Side Notes auto increment/decrement $i++; #same as $i = $i +1 $i--; chomp(STRING) and chop(STRING) chomp removes only 1 newline at end of string or variable (if one exists) chop removes last character of string

18 STDIN, STDOUT, Filehandles STDIN -- input "stream" (ex. keyboard -- are there others?) STDOUT -- output "stream" (ex. screen) Filehandles -- similar to streams -- input from, and output to files

19 More Side Notes chomp ($text = ); $text = ; chomp($text); # defined EXPR ; # returns a boolean value saying whether EXPR has a real value or not -- scalar with non-zero string or numeric $text = "hello"; if (defined($text)) { : } May be used to determine if subroutines or filehandle exists.

20 Filehandles name for a file, device, socket, or pipe filehandle name is arbitrary (one of few examples where $ is NOT used) open(FILE, "filename"); open(UP, "test"); # read from file "test" open(WRITE,">filename"); # write to file "filename" open(NOW, ">>test"); # append to a file close (FH);

21 Filehandles Examples # STDOUT is default output – to screen # STDIN is default input – from keyboard print STDOUT "Enter a number: "; $num = ; print STDOUT "the number is $num\n"; open(BOB, "test"); $line = ; #read one line from "test" open(NEW,">output"); print NEW "$line"; #write $line to file "output"

22 Pipes and File redirection | -- pipe operator (Unix) Example: File ("names") contains: Tim Tracy Bob cat names | sort > look Output: Bob Tim Tracy cat names | sort | wc > look > -- redirection operator ls > look Places files and directories into the file named “look”

23 Regular Expressions (regexp) Regular Expression – template that matches a set of strings –very useful for text processing and pattern matching document and text processing – text editors, etc formatted and unformatted data genomic data (sequences, ESTs, genes, microarray, etc) >gi| |ref|NM_ | Homo sapiens Bardet-Biedl syndrome 4 (BBS4), mRNA GACTTCCGGCCGCGCAGCGGTGGGCTGAGCTAAAATGGCTGAGGAGAGAGTCGCGACGAGAACTCAATTT CCTGTATCTACTGAGTCTCAAAAACCCCGGCAGAAAAAAGCTCCAGAGTTTCCTATTTTGG… default variable: $_ –in many cases, Perl will automatically use $_ as the default variable Examples: $_ = "test\n"; print; # prints $_ by default foreach (1..5) { # no variable specified print "Count $_ \n"; } $_ will show up more in later lectures

24 Pattern Matching To compare a pattern (regular expression): $_ = "ATCGAGAGCATGCCATGCAT"; if(/ATG/) { print "Found sequence\n"; } Remember naïve.pl

25 Regular Expressions metacharacters (.) period – matches any character except newline (\) backslash – makes any metacharacter a non-metacharacter Example: would match 3b145 3\.145 would match 3.145

26 Regular Expressions Quantifier metacharacters (*) asterisk – match preceding item 0 or more times /ATGC*ATG/ matches ATGATG, ATGCATG, ATGCCCCCCCCCCCCCCCCCCCCATG, etc. (+) plus – match preceding item 1 or more times (?) question mark – match preceding item 0 or 1 times /ATGC?ATG/ only matches ATGCATG and ATGATG

27 General Quantifiers /a{5,15}/ matches between 5, and 15 "a" matches if first 15, if more than 15 "a" /(fred){3,}/ matches 3 or more "fred" with no upper limit – fredfredfred /(fred){3}/ matches exactly fredfredfred * = {0,}zero or more + = {1,}one or more ? = {0,1}zero or one

#!/usr/bin/perl #ping for 1 week #every 5 minutes #12 per hour = 2016 pings $|=1; #output auto flush $num_pings=2016; $count = 0; $date = `date /t`; # Wed 09/17/2008 chomp($date); $date =~ s/(\w+)\s(\d+)\/(\d+)\/(\d+)(\s+)/$2$3$4/; $file = ">>PingLog".$date.".txt"; print "file = $file\n"; while($count<$num_pings) { print "pinging\n"; open(PING,$file); #$results = `ping `; $results = `ping `; #$results = system("ping "); print "results = $results\n"; $date = `date /t`; $time = `time /t`; $_ = $results; if(m/Reply/) { print PING "Success: $date $time $results\n"; } else { print PING "FAIL: $date $time $results\n"; } print PING " \n"; close(PING); $count++; $ticks = 150; # 2 * 150 = 300 secs = 5 mins while($ticks>0) { print "$count $ticks \r"; sleep(2); $ticks--; } print "\n"; } 28

FAIL: Wed 04/30/ :33 PM Pinging with 32 bytes of data: Request timed out. Ping statistics for : Packets: Sent = 4, Received = 0, Lost = 4 (100% loss), Success: Wed 04/30/ :38 PM Pinging with 32 bytes of data: Reply from : bytes=32 time=22ms TTL=51 Reply from : bytes=32 time=21ms TTL=51 Reply from : bytes=32 time=23ms TTL=51 Reply from : bytes=32 time=21ms TTL=51 Ping statistics for : Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 21ms, Maximum = 23ms, Average = 21ms

ping What the output of "ping" should look like: Pinging with 32 bytes of data: Reply from : bytes=32 time=24ms TTL=52 Ping statistics for : Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 22ms, Maximum = 25ms, Average = 23ms 30

Ping failure Pinging with 32 bytes of data: Request timed out. Ping statistics for : Packets: Sent = 4, Received = 0, Lost = 4 (100% loss), 31

32 END