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.

Slides:



Advertisements
Similar presentations
Ruby (on Rails) CSE 190M, Spring 2009 Week 2. Arrays Similar to PHP, Ruby arrays… – Are indexed by zero-based integer values – Store an assortment of.
Advertisements

Statement-Level Control Structures
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
More Perl Control Flow Software Tools. Slide 2 Control Flow l We have already seen several Perl control flow statements: n if n while n for n last l Other.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
CS 898N – Advanced World Wide Web Technologies Lecture 8: PERL Chin-Chih Chang
Starting Out with C++: Early Objects 5/e © 2006 Pearson Education. All Rights Reserved Starting Out with C++: Early Objects 5 th Edition Chapter 5 Looping.
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.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Logical Operators Java provides two binary logical operators (&& and ||) that are used to combine boolean expressions. Java also provides one unary (!)
Loops – While, Do, For Repetition Statements Introduction to Arrays
More Perl Control Flow Learning Objectives: 1. To learn more commands for control flow 2. To apply the new commands learnt for writing tidier program 3.
Loops Repetition Statements. Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional.
© 2004 Pearson Addison-Wesley. All rights reserved5-1 Iterations/ Loops The while Statement Other Repetition Statements.
More Perl Control Flow Learning Objectives: 1. To learn more commands for control flow 2. To apply the new commands learnt for writing tidier program 3.
CONTROL STATEMENTS Lakhbir Singh(Lect.IT) S.R.S.G.P.C.G. Ludhiana.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
Perl Tutorial Presented by Pradeepsunder. Why PERL ???  Practical extraction and report language  Similar to shell script but lot easier and more powerful.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
DiagrammaticRepresentation Iteration Construct False True Condition Exit from Statement (s) loop Sequence construct Selection construct Statement 1 Statement.
PL/SQL Loops. Building Logical Conditions All logical conditions must yield a boolean condition. You can build a simple Boolean condition by combining.
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.
Control Structures. if-elsif-else semantically the same as C/C++ syntactically, slightly different. if ($a > 0){ print “\$a is positive\n”; } elsif ($a.
PHP Conditional Statements Conditional statements in PHP are used to perform different actions based on different conditions. Conditional Statements Very.
PHP Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
COMPUTER PROGRAMMING. Iteration structures (loops) There may be a situation when you need to execute a block of code several number of times. In general,
What does C store? >>A = [1 2 3] >>B = [1 1] >>[C,D]=meshgrid(A,B) c) a) d) b)
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Week 3 - Wednesday.  What did we talk about last time?  Other C features  sizeof, const  ASCII table  printf() format strings  Bitwise operations.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Chapter 9: Perl (continue) Advanced Perl Programming Some materials are taken from Sams Teach Yourself Perl 5 in 21 Days, Second Edition.
Revision Lecture Mauro Jaskelioff. AWK Program Structure AWK programs consists of patterns and procedures Pattern_1 { Procedure_1} Pattern_2 { Procedure_2}
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
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
CS 105 Perl: Data Types Nathan Clement 15 May 2014.
5 1 Data Files CGI/Perl Programming By Diane Zak.
JavaScript, Fourth Edition
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
 2000 Deitel & Associates, Inc. All rights reserved. Chapter 10 - JavaScript/JScript: Control Structures II Outline 10.1Introduction 10.2Essentials of.
CPTG286K Programming - Perl Chapter 4: Control Structures.
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,
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
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.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
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 for Bioinformatics Part 2 Stuart Brown NYU School of Medicine.
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.
Week 3 - Friday.  What did we talk about last time?  Preprocessor directives  Other C features  sizeof, const  ASCII table  printf() format strings.
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.
CPTG286K Programming - Perl Chapter 9: Misc. Control Structures Chapter 10: Filehandles & File tests.
BLOCK  is enclosed by curly brackets {}.  Keep in mind that blocks are always bounded by curly brackets, even if your block has only one code line.
Perl Subroutines User Input Perl on linux Forks and Pipes.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Introduction to Loop. Introduction to Loops: The while Loop Loop: part of program that may execute > 1 time (i.e., it repeats) while loop format: while.
Program with PL/SQL Lesson 4.
Loops BIS1523 – Lecture 10.
Chapter 5 - Control Structures: Part 2
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
CIT 383: Administrative Scripting
Control Structures: for & while Loops
Context.
Presentation transcript:

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 language –Can make your code look more like C

Conditionals Flow of control changes based on conditionals No special type, just a scalar value –Parts of the code that require a conditional are evaluated as scalar context –False : zero or empty string –True : anything else –Undefined will be treated as false –Empty arrays and hashes evaluate to zero in a scalar context, so they behave like false.

Two kinds of conditional operators Perl supports C/C++ operators &&, || and ! Perl also supports operators and, or, not Both types of operators are short-circuiting The and, or and not have lower precedence than &&, || and ! –So, they don't bind as tightly –Both kinds of can be combined into large conditional expressions –In some cases, and, or and not are used to promote readability With short circuiting, and and or are often used to implement guards. # exit with a failure message if $i isn't 25 $i == 25 or die "Ouch\n";

If Statement Syntax is very similar to C/C++ Example: if ( $i < 25 ) { print "i is kind of small\n"; } The curly brackets are always required

If and Else If can be followed by elsif and else. Notice the peculiar spelling for elsif. if ( $i > 30 ) { print "i is big\n"; } elsif ( $i > 20 ) { print "i is medium\n"; } else { print "i is small\n"; }

Alternatives to the If Perl provides lots of alternative syntax for the same (or similar) things Unless statement is like if, but the sense of the conditional is reversed unless ( $i >= 25 ) { print "i is kind of small\n"; }

Statement Modifiers Statement modifier, yet another way to write a conditional statement Written at the end of a statement to control when it executes. Any simple statement may be followed by a modifier. # Decrement $i if it's larger than 25 $i -= 1 if $i > 25; # Increment $i if it's less than 25 $i += 1 unless $i >= 25;

Looping Perl supports many looping constructs –for –while –until –do while –do until –foreach All require a block statement for a body (i.e. they require curlies around the body)

For Loop Syntax like C. for ( $i = 0; $i < 25; $i++ ) { print "$i\n"; } for ( $i = 0; $i $i++ ) { print "$seq[ $i ]\n"; }

While loop Syntax like C my $total = 0; while ) { $total += $vlist[ 0 ]; }

Looping with Lables We can label some loops so we can jump to the next iteration. Label is just an identifier for the loop ROW: while ( $i < 25 ) { # pretend there's some code here. } Inside the body, we can jump to the next iteration of loop labeled ROW: next ROW;

Continue Blocks While and foreach can have continue blocks –These provide a block of code to perform before the next iteration, even if we execute a next. ROW: while ( $i < 25 ) { # pretend there's some code here. } continue { $i++; }

Looping with Labels my $i = 0; OUTER: while ( $i < 10 ) { my $j = 0; INNER: while ( $j < 10 ) { print "$j "; next OUTER if $j == $i; $j++; } } continue { print "\n"; $i++; } Prints out:

until loop Like a while loop, but loop as long as the condition is false my $i = 0; until ( $i >= 10 ) { print "$i\n"; $i++; }

Do While Test-at-the-end variant of the while loop Will always execute the body at least once # this loop will print a 10. my $i = 10; do { print "$i\n"; $i++; } while ( $i < 10 );

Do Until Test-at-the-end variant of the until loop Will always execute at least once # This loop will print a 10 my $i = 10; do { print "$i\n"; $i++; } until ( $i >= 10 );

Foreach loop Made for iterating over lists # $i takes on each value in # then the body is executed foreach $i { print "$i\n"; } Like while, we can have a continue block Loop variable is a modifiable lvalue –It changes the contents of the list if you modify it. –Can use this to change the list as you traverse it Omitting the loop variable uses $_, the default scalar var foreach is just a synonym for for # Use the default variable to iterate over a list for ) { # append " ice cream" to each array element. $_.= " ice cream"; }

Looping Statement Modifiers Like the conditional modifiers simple-stmt while conditional; simple-stmt until conditional; simple-stmt foreach list; These can execute the stmt multiple times. Here, while and until tests are applied before the statement, they are not test-at-the-end loops

Looping Statement Modifiers For example: # Print each element # We are depending on the default scalar # value here, which is also the default # parameter for print. print # This is a little better since it gives # us newlines between each element. print "$_\n"

Fun with what we know # make a list of values, 1 - = (1..10); # An obvious way to print them out. for ( $i = 0; $i $i++ ) { print "$vlist[ $i ] "; # Print a newline every 5th item. print "\n" if $i % 5 == 4; } # Show off how we can change the list. foreach $val { # double each value if it's odd $val *= 2 unless $val % 2 == 0; } # Another way to print them out. foreach { print; print "\n"; } Source Code Output

Perl an I/O We can open files with the open procedure File name decides the mode # open for reading. open( INPUT, "file.txt" ); # open for writing. open( OUTPUT, ">file2.txt" ); # open for reading and writing. open( DATAFILE, "+ >file4.txt" ); First parameter to open is a file handle –File handle gives us a way to talk about the file –Close the file using the same handle: close OUTPUT;

Sending output to a file Print takes an optional output file handle parameter print OUTPUT "Testing $a $b $c\n"; If no handle is given, stdout is used.

Reading Input from a file Operator reads from a file. Context determines how much you read. # read just one line $line = ; # read the whole file as an array of = ; Lines read from input still have eoln at the end –Can remove it with chomp (from last lesson) –chomp $line;

Reading From a File A blank line will be read as a sting containing just eoln End of file will be read in as an empty string, which looks like false to a conditional. We can use this to govern a loop: $line = ; # While we got some input. while ( $line ) { # print the input (newline is still on it) print $line; # read the next line $line = ; }

Reading from a file We can shorten this with: while ( $line = ) { print $line; } Read reads into $_ by default So we can write even shorter code as: while ( ) { print; }

Working with Input If we want to process input lines, we may have to work with them a bit –We can use the chomp function to strip off eoln at the end (if it ends with one) chomp $line; –Use split to split a line into fields based on some field = split( / +/, $line ); –The first parameter here is really a regular expression, describing what the breaks between fields should look like. –split returns a list of fields, each separated by the given regular expression

Input Example # open an input file open( INPUT, "paper.txt" ); # read each of its lines while ( $line = ) { #strip off the newline if it's there. chomp $line; # Break lines into space-separated = split( / +/, $line ); # print out each word on its own line. print "$_\n" }