Control Structures. Important Semantic Difference

Similar documents
Subroutines. Subroutines. The Basics. aka: user-defined functions, methods, procdures, sub-procedures, etc etc etc.

Repetition Structures

Condition-Controlled Loop. Condition-Controlled Loop. If Statement. Various Forms. Conditional-Controlled Loop. Loop Caution.

Introduction. C provides two styles of flow control:

A control expression must evaluate to a value that can be interpreted as true or false.

(Refer Slide Time: 01:12)

Chapter 2: Functions and Control Structures

Control Structures. Code can be purely arithmetic assignments. At some point we will need some kind of control or decision making process to occur

Lexical Considerations

NAME DESCRIPTION. Declarations. Perl version documentation - perlsyn. perlsyn - Perl syntax

Examples of Using the ARGV Array. Loop Control Operators. Next Operator. Last Operator. Perl has three loop control operators.

Review of the C Programming Language for Principles of Operating Systems

Learning Perl 6. brian d foy, Version 0.6, Nordic Perl Workshop 2007

COMP284 Scripting Languages Lecture 3: Perl (Part 2) Handouts

Lexical Considerations

Chapter 13 Control Structures

Ruby: Introduction, Basics

G Programming Languages - Fall 2012

Chapter 8. Statement-Level Control Structures

NAME DESCRIPTION. Declarations. Perl version documentation - perlsyn. perlsyn - Perl syntax

Expressions vs statements

CSCI 4152/6509 Natural Language Processing. Perl Tutorial CSCI 4152/6509. CSCI 4152/6509, Perl Tutorial 1

Programming for Electrical and Computer Engineers. Loops

Chapter 8 Statement-Level Control Structures

Chapter 6. Loops. Iteration Statements. C s iteration statements are used to set up loops.

1 Lexical Considerations

Scripting Languages Perl Basics. Course: Hebrew University

GNU ccscript Scripting Guide IV

Definition: A data structure is a way of organizing data in a computer so that it can be used efficiently.

Chapter 7. - FORTRAN I control statements were based directly on IBM 704 hardware

Review of the C Programming Language

Flow Control. CSC215 Lecture

The Power of Perl. Perl. Perl. Change all gopher to World Wide Web in a single command

x = 3 * y + 1; // x becomes 3 * y + 1 a = b = 0; // multiple assignment: a and b both get the value 0

Loop structures and booleans

Perl. Interview Questions and Answers

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Chapter 13. Control Structures

Indian Institute of Technology Kharagpur. PERL Part II. Prof. Indranil Sen Gupta Dept. of Computer Science & Engg. I.I.T.

COMS 3101 Programming Languages: Perl. Lecture 2

An Introduction to Scheme

Rule 1-3: Use white space to break a function into paragraphs. Rule 1-5: Avoid very long statements. Use multiple shorter statements instead.

JME Language Reference Manual

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

CS 230 Programming Languages

CSc 520 Principles of Programming Languages. 26 : Control Structures Introduction

Intro. Scheme Basics. scm> 5 5. scm>

Accelerating Information Technology Innovation

SEER AKADEMI LINUX PROGRAMMING AND SCRIPTINGPERL 7

REPETITIVE EXECUTION: LOOPS

Statement level control structures

The Perl Debugger. Avoiding Bugs with Warnings and Strict. Daniel Allen. Abstract

Chapter 8. Statement-Level Control Structures

package YourModule; require = = qw(munge frobnicate); # symbols to export on request

Le L c e t c ur u e e 3 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Control Statements

Ch. 7: Control Structures

Chapter 13 Control Structures

Modularity and Reusability I. Functions and code reuse

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

COMP 110/L Lecture 10. Kyle Dewey

PLT Fall Shoo. Language Reference Manual

STUDENT OUTLINE. Lesson 8: Structured Programming, Control Structures, if-else Statements, Pseudocode

Ruby: Introduction, Basics

IT441. Subroutines. (a.k.a., Functions, Methods, etc.) DRAFT. Network Services Administration

Sequence structure. The computer executes java statements one after the other in the order in which they are written. Total = total +grade;

Programming Languages Third Edition. Chapter 9 Control I Expressions and Statements

Ruby: Introduction, Basics

Midterm Exam. 5. What is the character - (minus) used for in JavaScript? Give as many answers as you can.

Chapter 7 Control I Expressions and Statements

Classes Nov 3, Ch

Introduction to C Programming

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

Control Structures. Outline. In Text: Chapter 8. Control structures Selection. Iteration. Gotos Guarded statements. One-way Two-way Multi-way

C/C++ Programming for Engineers: Matlab Branches and Loops

Chapter 8. Statement-Level Control Structures

Coding Standard for ECE3090 August 24, 2005

C++ Programming: From Problem Analysis to Program Design, Third Edition

bash Execution Control COMP2101 Winter 2019

More Perl. CS174 Chris Pollett Oct 25, 2006.

Accelerating Information Technology Innovation

Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

perl -MO=Deparse[,-d][,-fFILE][,-p][,-q][,-l] [,-sletters][,-xlevel] prog.pl

Basic computer skills such as using Windows, Internet Explorer, and Microsoft Word. Chapter 1 Introduction to Computers, Programs, and Java

CS 4240: Compilers and Interpreters Project Phase 1: Scanner and Parser Due Date: October 4 th 2015 (11:59 pm) (via T-square)

GAWK Language Reference Manual

Programming for Engineers Iteration

Introduction to Perl Session 6. special variables subroutines Introduction to Perl

Program Abstractions, Language Paradigms. CS152. Chris Pollett. Aug. 27, 2008.

5 The Control Structure Diagram (CSD)

Accelerating Information Technology Innovation

Quiz 1: Functions and Procedures

Python Programming: An Introduction To Computer Science

Flow of Control Execution Sequence

Definite Loops. Computer Science S-111 Harvard University David G. Sullivan, Ph.D. Using a Variable for Counting

Perl. Many of these conflict with design principles of languages for teaching.

This book is licensed under a Creative Commons Attribution 3.0 License

Defining Program Syntax. Chapter Two Modern Programming Languages, 2nd ed. 1

@EXPORT_OK = qw(munge frobnicate); # symbols to export on request

Control Flow. COMS W1007 Introduction to Computer Science. Christopher Conway 3 June 2003

Key Points. COSC 123 Computer Creativity. Java Decisions and Loops. Making Decisions Performing Comparisons. Making Decisions

Transcription:

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"; 1

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 (<$fh>) { perl automatically translates this to: while (defined($_ = <$fh>)) { $_ holds the line that was just read. When <$fh> returns undef (ie, file completely read), loop terminates. This does NOT happen anywhere else! <$fh>; Reads a line and throws it away, does NOT assign to $_ while (<$fh> and $x > $y) { Reads a line, throws it away. Compares $x to $y. Does not assign to $_ 2

do Execute all statements in following block, and return value of last statement executed When modified by while or until, run through h 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, g and the loop body executed my $sum; foreach my $value (@nums){ $sum += $value; 3

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 (@array) { but this is just as syntactically valid: foreach (my $i = 0; $i<10; $i++) { for my $elem (@array) { 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 my @array = (1, 2, 3, 4, 5); foreach my $num (@array) { $num *= 2; @array now (2, 4, 6, 8, 10) if VAR omitted, $_ used instead my $sum = 0; foreach (@array) { $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. 4

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 (<$fh>){ vs while (<$fh>){ 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 <$fh> in list context, once while's condition is defined($_ = <$fh>) evaluates <$fh> 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 (<$fh>) { 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 (@nums) { say '@nums 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 5

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 (@students) { 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 t the current loop, without t 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) 6

Breaking Out of More Loops next, last, redo operate on innermost loop Labels are needed to break out of nesting loops TOP: while ($i < 10){ MIDDLE: while ($j > 20) { BOTTOM: for (@array){ if ($_ == $i * $j){ last TOP; if ($i * 3 > $_){ next MIDDLE; $j--; $i++; yes, it exists. No, don t use it. goto 7