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.

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

Statement-Level Control Structures
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.
(8.1) COEN Control Structures  Control structure general issues  Compound statements  Selectors (conditional structures) – single – two-way –
Creating PHP Pages Chapter 7 PHP Decisions Making.
PHP Functions and Control Structures. 2 Defining Functions Functions are groups of statements that you can execute as a single unit Function definitions.
CS 330 Programming Languages 10 / 14 / 2008 Instructor: Michael Eckmann.
Homework Any Questions?. Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used.
Computer Science 1620 Loops.
CS 106 Introduction to Computer Science I 02 / 12 / 2007 Instructor: Michael Eckmann.
Python November 18, Unit 7. So Far We can get user input We can create variables We can convert values from one type to another using functions We can.
ECE122 L11: For loops and Arrays March 8, 2007 ECE 122 Engineering Problem Solving with Java Lecture 11 For Loops and Arrays.
Statement-Level Control Structures Sections 1-4
ISBN Chapter 8 Statement-Level Control Structures.
Objectives You should be able to describe:
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.
© 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.
Subroutines. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc We’ll just say Subroutines. –“Functions” generally means built-in.
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.
COMPUTER PROGRAMMING. Control Structures A program is usually not limited to a linear sequence of instructions. During its process it may repeat code.
REPETITION CITS1001. Scope of this lecture Repetition for loops while loops 2.
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.
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 Programming with MySQL Slide 4-1 CHAPTER 4 Functions and Control Structures.
C# Programming Fundamentals Control Flow Jim Warren, COMPSCI 280 S Enterprise Software Development.
Chapter 2 Functions and Control Structures PHP Programming with MySQL 2 nd Edition.
Chapter 8 Chapter 8 Control Structures. Control Structures  A control structure is a control statement and the statements whose execution it controls.
Current Assignments Homework 2 is available and is due in three days (June 19th). Project 1 due in 6 days (June 23 rd ) Write a binomial root solver using.
1 CS Programming Languages Class 11 September 26, 2000.
Controlling Execution Dong Shao, Nanjing Unviersity.
1 Conditionals In many cases we want our program to make a decision about whether a piece of code should be executed or not, based on the truth of a condition.
CSI 3120, Control, page 1 Control statements Simple statements Basic structured statements Sequence Selection Iteration The jump statement.
Introduction to Unix – CS 21
8-1 Statement-Level Control Structures Introduction Selection Statements Iterative Statements Unconditional Branching Guarded Commands Conclusions.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Perl Tutorial. Why PERL ??? Practical extraction and report language Similar to shell script but lot easier and more powerful Easy availablity All details.
CPTG286K Programming - Perl Chapter 4: Control Structures.
CS 105 Perl: Basic I/O, Context, Strings, Lists Nathan Clement January 22, 2014.
Chapter 15 JavaScript: Part III The Web Warrior Guide to Web Design Technologies.
Selection Statements. Introduction Today we learn more about learn to make decisions in Turing ▫Nested if statements, ▫case statements.
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.
1 Iterative Statements Repeated execution of a (compound) statement by iteration or recursion –Iteration is statement level –Recursion is unit-level control.
Introduction to Loops Iteration Repetition Counting Loops Also known as.
Loops Robin Burke IT 130. Outline Announcement: Homework #6 Conditionals (review) Iteration while loop while with counter for loops.
CPS120 Introduction to Computer Science Iteration (Looping)
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
 In computer programming, a loop is a sequence of instruction s that is continually repeated until a certain condition is reached.  PHP Loops :  In.
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.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
W E E K F I V E Control Flow. Copyright © 2006 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements Iterative Statements.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
JavaScript, Sixth Edition
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.
Operators. Perl has MANY operators. –Covered in Chapter 3 of Camel –perldoc perlop Many operators have numeric and string version –remember Perl will.
Unit – 3 Control structures. Condition Statements 1.If.…..else :- Has someone ever told you, "if you work hard, then you will succeed"? And what happens.
Chapter 8 Statement-Level Control Structures. Copyright © 2012 Addison-Wesley. All rights reserved.1-2 Chapter 8 Topics Introduction Selection Statements.
Today… Preparation for doing Assignment 1. Invoking methods overview. Conditionals and Loops. Winter 2016CMPE212 - Prof. McLeod1.
Learning Javascript From Mr Saem
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
JavaScript: Control Statements.
Chapter 8: Control Structures
Control Structures: for & while Loops
Context.
Statement-Level Control Structures
REPETITION Why Repetition?
Chapter 13 Control Structures
Presentation transcript:

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 only has one statement, you must include the braces.

if-elsif-else semantically the same as C/C++ syntactically, slightly different. –note the spelling of elsif if ($a > 0){ print "\$a is positive\n"; } elsif ($a == 0){ print "\$a equals 0\n"; } else { print "\$a is negative\n"; }

unless another way of writing if (!…) {…} analogous to English meaning of "unless" unless (EXPR) BLOCK –"do BLOCK unless EXPR is true" –"do BLOCK if EXPR is false" can use elsif and else with unless as well –caution - elsif is still an if. It's not an elsunless.

while/until loops while (EXPR) BLOCK –"While EXPR is true, do BLOCK" –Check the condition. If it's true, do the block. Repeat. until (EXPR) BLOCK –"Until EXPR is true, do BLOCK" –"While EXPR is false, do BLOCK" –another way of saying while (!…) {…} –Check the condition. If it's false, do the block. Repeat.

while magic If and only if the only thing within the condition of a while loop is the readline operator: while ( ) { } perl automatically translates this to: while (defined($_ = )) { } –$_ holds the line that was just read. –When returns undef (ie, file completely read), loop terminates. This does NOT happen anywhere else! – ; Reads a line and throws it away, does NOT assign to $_ –while ( and $x > $y) { } Reads a line, throws it away. Compares $x to $y. Does not assign to $_

do Execute all statements in following block, and return value of last statement executed When modified by while or until, run through block once before checking condition do { $i++; } while ($i < 10);

for loops Perl has 2 styles of for. First kind is virtually identical to C/C++ for (INIT; TEST; INCREMENT) { } for (my $i = 0; $i < 10; $i++){ print "\$i = $i\n"; } perform the initialization. Check the test. If it's true, do the block, then increment. Check the test. etc.

foreach loops Second kind of for loop in Perl –no equivalent in core C/C++ language foreach VAR (LIST) {} each member of LIST is assigned to VAR, and the loop body executed my $sum; foreach my $value $sum += $value; }

More About for/foreach for and foreach are synonyms –Anywhere you see "for" you can replace it with "foreach" and viceversa Without changing ANYTHING ELSE –they can be used interchangeably. –usually easier to read if conventions followed: for (my $i = 0; $i<10; $i++) {} foreach my $elem {} –but this is just as syntactically valid: foreach (my $i = 0; $i<10; $i++) {} for my $elem {}

foreach triviata foreach VAR (LIST) {} while iterating through list, VAR becomes an *alias* to each member of LIST –Changes to VAR within the loop affect LIST = (1, 2, 3, 4, 5); foreach my $num { $num *= 2; } now  (2, 4, 6, 8, 10) if VAR omitted, $_ used instead –my $sum = 0; foreach { $sum += $_; }

foreach loop caveat my $num = 'alpha'; for $num (0..5) { print "num: $num\n"; } Upon conclusion of the loop, $num goes back to 'alpha'! –The for loop creates its own lexical variable, even though you didn't specify for my $num (0..5) { … } For this reason, it is always preferred to *explicitly* declare the variable lexical to the loop, to avoid the possible confusion.

Best Practice There is *rarely* any need to use C-style for loops in Perl If you want to iterate over a count value: –foreach my $count (1..$total) { } –foreach my $i (0..$#array) { } Only time you need a C-style for loop is to increment by something other than 1: –for (my $v=0; $v < $tot; $i+=3) { }

foreach ( ){ } vs while ( ){ } Both constructs appear to do the same thing. –Assign each line of $fh to $_, execute loop body The difference is internal –foreach takes a LIST evaluates in list context, once –while 's condition is defined($_ = ) evaluates in scalar context, repeatedly foreach will read the entire file into memory at once –each element of resulting list is then assigned to $_ while will read the file line by line, discarding each line after it's read –FAR more efficient. Always use while ( ) { }

given (5.10 exclusive) Compare one variable against a series of different values/conditions use feature ':5.10'; given ($foo) { when (5) { say '$foo == 5'; } when ('abc') { say '$foo eq "abc"'; } when (undef) { say '$foo is undefined'; } when { say contains $foo'; } when (%age_of) { say '$foo is key in %age_of; } when ($_ > 100) { say '$foo > 100'; } when ($_ lt 'xyz') { say '$foo lt "xyz"'; } default { say 'I know nothing about $foo; } } given an array, can check for identical array or an element given a hash, can check for identical keys or a key's existence

given fallthrough Fallthrough does not happen by default. As soon as one when matches, given terminates. To continue checking other conditions, end with continue; given { when ('Joe') { say 'Joe is in the class'; continue; } when ('Mary') { say 'Mary is in the class'; continue; } when ('Adam') { say 'Adam is in the class'; } } To terminate the when and entire given blocks early, use break Warning - these are only valid for given/when - they don't have the same effects you'd expect from the C/C++ versions.

Reading it in English Perl has a cute little feature that makes simple loop constructs more readable If your if, unless, while, until, or foreach block contains only a single statement, you can put the condition at the end of the statement: if ($a > 10) {print "\$a is $a\n";} print "\$a is $a\n" if $a > 10; Using this modifier method, braces and parentheses are unneeded This is syntactic sugar – whichever looks and feels right to you is the way to go.

Loop Control – next, last, redo last  exit innermost loop –equivalent of C++ break next  begin next iteration of innermost loop –(mostly) equivalent of C++ continue redo  restart the current loop, without evaluating conditional –no real equivalent in C++ Note that Perl does not consider do to be a looping block. Hence, you cannot use these keywords in a do block (even if it’s modified by while)

Breaking Out of More Loops next, last, redo operate on innermost loop Labels are needed to break out of nesting loops TOP: while ($i 20) { BOTTOM: for if ($_ == $i * $j){ last TOP; } if ($i * 3 > $_){ next MIDDLE; } } $j--; } $i++; }

goto yes, it exists. No, don’t use it.