CPTG286K Programming - Perl Chapter 9: Misc. Control Structures Chapter 10: Filehandles & File tests.

Slides:



Advertisements
Similar presentations
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.
Advertisements

Computer programming Lecture 3. Lecture 3: Outline Program Looping [Kochan – chap.5] –The for Statement –Relational Operators –Nested for Loops –Increment.
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.
Perl File I/O Learning Objectives: 1. To understand the usage of file handler in Perl 2. To learn the file error handling / testing in Perl.
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Starting Out with C++ Early Objects Sixth Edition Chapter 5: Looping by Tony.
Iteration This week we will learn how to use iteration in C++ Iteration is the repetition of a statement or block of statements in a program. C++ has three.
Chapter 5: Loops and Files.
Perl File I/O Software Tools. Slide 2 Filehandles l A filehandle is the name for an I/O connection between your Perl program and the outside world. STDIN.
CS 1 Lesson 5 Loops and Files CS 1 -- John Cole.
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.
Perl - Advanced More Advanced Perl  Functions  Control Structures  Filehandles  Process Management.
Introduction to Computer Programming in c
Chapter 5: Control Structures II (Repetition)
Chapter 4: Decision Making with Control Structures and Statements JavaScript - Introductory.
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 Week Introduction -Representation of the theory and principles of structured programming. Demonstration of for, while,do…whil.
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.
Copyright © 2010 Certification Partners, LLC -- All Rights Reserved Perl Specialist.
1 Additional Control Structures. 2 Chapter 9 Topics  Switch Statement for Multi-way Branching  Do-While Statement for Looping  For Statement for Looping.
Chapter 8 Iteration Dept of Computer Engineering Khon Kaen University.
 2008 Pearson Education, Inc. All rights reserved JavaScript: Control Statements I.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Prof. Alfred J Bird, Ph.D., NBCT Office – McCormick 3rd floor 607 Office Hours – Tuesday and.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 5 Looping.
+ Starting Out with C++ Early Objects Seventh Edition by Tony Gaddis, Judy Walters, and Godfrey Muganda Chapter 5: Looping.
5 1 Data Files CGI/Perl Programming By Diane Zak.
MATHEMATICA – AN INTRODUCTION R.C. Verma Physics Department Punjabi University Patiala – PART IV- Programming in Mathematica Input and Output Logical.
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.
CPTG286K Programming - Perl Chapter 1: A Stroll Through Perl Instructor: Denny Lin.
Topic 2: Working with scalars CSE2395/CSE3395 Perl Programming Learning Perl 3rd edition chapter 2, pages 19-38, Programming Perl 3rd edition chapter.
Loops and Files. 5.1 The Increment and Decrement Operators.
1 Standard Version of Starting Out with C++, 4th Brief Edition Chapter 5 Looping.
Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 5: Looping.
Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 5 Looping.
1 Programming in C++ Dale/Weems/Headington Chapter 9 Additional Control Structures (Switch, Do..While, For statements)
Chapter Looping 5. The Increment and Decrement Operators 5.1.
9. ITERATIONS AND LOOP STRUCTURES Rocky K. C. Chang October 18, 2015 (Adapted from John Zelle’s slides)
Perl Scripting II Conditionals, Logical operators, Loops, and File handles Suzi Lewis Genome Informatics.
Copyright 2006 Addison-Wesley Brief Version of Starting Out with C++ Chapter 5 Looping.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Files A collection of related data treated as a unit. Two types Text
Engineering Computing I Chapter 3 Control Flow. Chapter 3 - Control Flow The control-flow of a language specify the order in which computations are performed.
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Extended Prelude to Programming Concepts & Design, 3/e by Stewart Venit and.
Perl Chapter 3 Conditional statements. Control Expressions Control expressions – interpreted as T/F (evaluated as strings or numbers) – simple, relational,
Chapter Looping 5. The Increment and Decrement Operators 5.1.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 6.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Repetition statements
Chapter 4 – C Program Control
Input from STDIN STDIN, standard input, comes from the keyboard.
Chapter 5 - Control Structures: Part 2
JavaScript: Control Statements I
Miscellaneous Items Loop control, block labels, unless/until, backwards syntax for “if” statements, split, join, substring, length, logical operators,
Review If you want to display a floating-point number in a particular format use The DecimalFormat Class printf A loop is… a control structure that causes.
Chapter 5: Loops and Files.
Chapter 5: Looping Starting Out with C++ Early Objects Seventh Edition
JavaScript: Control Statements.
Chapter 5: Looping Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
Topics Introduction to File Input and Output
Iteration: Beyond the Basic PERFORM
Lab5 PROGRAMMING 1 Loop chapter4.
2.6 The if/else Selection Structure
Topics Introduction to File Input and Output
Chapter 8 JavaScript: Control Statements, Part 2
Presentation transcript:

CPTG286K Programming - Perl Chapter 9: Misc. Control Structures Chapter 10: Filehandles & File tests

The last statement The last statement causes an exit from the innermost enclosing loop block Execution continues with the statement immediately following the loop block Can only be used inside a loop block (aka bare or naked block*) * Blocks in do{}, eval{}, if{}, unless{}, and sub{} are NOT loop, bare, or naked blocks

Example using last statement #!/usr/bin/perl -w $something = 1;# Initialize $something to true while ($something)# Loop until $something is false { print "Enter a number: ";# prompt for input chomp ($something = );# strip newline print "\n\$something: $something\n";# show contents if ($something == 50)# breakout condition { print "Breaking out of while loop...\n"; last;# do breakout } print "Still in while loop.\n";# loop indicator } print "Outside while loop!\n";# loop exit indicator

Placing last in a do {} block #!/usr/bin/perl -w $something = 1;# Initialize $something to true {# Make a bare or naked block do{ print "Enter a number: ";# prompt for input chomp ($something = );# strip newline print "\n\$something: $something\n";# show contents if ($something == 50)# breakout condition { print "Breaking out of bare block...\n"; last;# do{} is inside a bare block }# skips next two print statements print "Still in do{} while block.\n";# loop indicator } while ($something);# while $something is true print "Exiting do{} while block\n";# when $something is false } print "Outside bare block!\n";# bare block exit indicator

The next statement The next statement starts the next iteration, skipping any remaining statements in the innermost enclosing looping block Can only be used inside a loop block If there is a continue {} block for the loop, next executes the continue block before going to the end of the loop block

Example using next statement #!/usr/bin/perl -w $something = 1;# Initialize $something to true while ($something)# Loop until $something is false { print "Enter a number: ";# prompt for input chomp ($something = );# strip newline print "\n\$something: $something\n";# show contents if ($something == 50)# next condition { print "Skipping rest of while loop...\n"; next;# go to next iteration } print "The rest of the while loop.\n";# rest of the loop } continue { print "Inside continue block\n";# shown on every iteration } print "Outside while loop!\n";# loop exit indicator

Placing next in a do {} block #!/usr/bin/perl -w $something = 1;# Initialize $something to true do { {# Make bare block within do{} block print "Enter a number: ";# prompt for input chomp ($something = );# strip newline print "\n\$something: $something\n";# show contents if ($something == 50)# next condition { print "Skipping rest of bare block...\n"; next;# go to next iteration } print "The rest of do{} while block.\n";# rest of block } } while ($something); print "Outside bare block!\n";# bare block exit indicator

The redo statement The redo statement causes a loop block to restart without reevaluating the control expression #!/usr/bin/perl -w $something = 1;# Initialize $something to 1 while ($something 5 { if ($something 10 { print "$something ";# Print value of $something ++$something;# Increment $something redo;# Skips the while condition test } print "\n\$something is now $something\n";# $something is now 11

Placing redo in a do {} block #!/usr/bin/perl -w $something = 1;# Initialize $something to 1 do { {# Make bare block within do {} block if ($something 10 { print "$something ";# Print value of $something ++$something;# Increment $something redo;# Skips the while condition test } } while ($something 5 print "\n\$something is now $something\n";# $something is now 11

Labeled Blocks Labeled blocks are used by last, next, and redo to jump outside of the innermost loop block Block names have no prefix characters, so it is best to choose uppercase names for blocks Place label in front of statement containing the block followed by a colon Call the block as a parameter of last, next, or redo

Example of Labeled blocks #!/usr/bin/perl -w OUTER: for ($i = 1; $i <= 10; $i ++) { print "\$i: $i "; # Display outer loop index INNER: for ($j = 1; $j <= 10; $j++) { print "\$j: $j "; # Display inner loop index if ($i * $j == 63)# End condition { print "$i times $j is 63!\n"; last OUTER; # Break out of loops } if ($j >= $i)# Inner loop >= outer loop { print "\n"; # Print newline next OUTER; # Skip inner loop }

Expression Modifiers PERL allows if, unless, while, and until expressions to be modified in the form: simple_expression if control_expression; simple_expression unless control_expression; simple_expression while control_expression; simple_expression until control_expression; A simple expression does not contain a block of statements These expressions do not nest (they are not statements)

Expression Modifiers Examples ++counter if (counter < 50);# increment counter # if it's below 50 --counter if (counter > 500);# decrement counter # if it's over 500 $index *= 2 while $index > 10;# double index while # it's over 10 $index /= 2 until $index = 0;# halve index until # it's 0

The && as control structure An if operator is analogous to an && operator: –if control_expression is true, simple_expression is performed; control_expression not performed –if control_expression is false, simple_expression is not performed; control_expression performed Thus, the following are equivalent: –if ($this == 5) { print "$that\n"; } –($this == 5) && print "$that\n";

The || as control structure An unless operator is analogous to an || operator: –if control_expression is false, simple_expression is performed; control_expression is NOT performed –if control_expression is true, simple_expression is NOT performed; control_expression is performed Thus, the following are equivalent: –unless ($this == 5) { print "$that\n"; } # if ($this != 5) –($this == 5) || print "$that\n";# "one or the other" Note: "unless" is logically equivalent to "if not"

Filehandles Filehandles establish an Input/Output connection between a PERL program and the outside world PERL built-in filehandles are: STDIN, STDOUT, and STDERR User-defined filehandles are creating with the open() function, and closed using the close() function

Opening filehandles Create a filehandle named FHANDLENAME using open(FHANDLENAME,"filename"); this opens filename for reading To open the file for writing, add a greater-than sign prefix to the filename: open(FHANDLENAME,">filename"); To append to the file, add two greater-than sign prefixes to the filename: open(FHANDLENAME,">>filename");

Closing a filehandle Reopening a filehandle will automatically close the previously open file. All open filehandles are automatically closed when program exits To flush out all data before program termination, close filehandle using close(FHANDLENAME);

Filehandle die and warn Both open() and close() functions return a success or failure Use the || control structure and die or warn to display the status of operation The $! variable displays the operating system error open(AFILE,"file") || die "Open file failed: terminating program: $!"; # Terminates program displaying file and line number of program open(AFILE,"file") || die "Open file failed: terminating program\n"; # Terminates program without displaying file and line number of program open(AFILE,"file") || warn " Open file failed: $!"; # Does not exit program after error message

Using filehandles Once a file has been opened for reading, its contents can be read, and written into another file open for writing: $infile = "inputfile"; $outfile = "outputfile"; open(IN, $infile) || die "Cannot open $infile: $!"; open(OUT, ">$outfile") || die "Cannot open $outfile: $!"; while ( ) { print OUT $_; } close (IN) || die "can't close $infile: $!"; close (OUT) || die "can't close $outfile: $!";

File Tests The attributes of a file can be examined by a file test operator File tests can operate on a scalar variable, filehandle, or a filename File/directory tests include –r for readable, -w for writable, –x for executable, and -e for exists (see complete list in table 10-1) $name = "index.html";# Specify file if (-e $name)# File exists test { print "Found $name!\n"; }# Display finding

The stat and lstat functions In list context, these functions return statistics of a file There are 13 fields returned as a list Can use slice access to get specific file info Use lstat to access symbolic link information (not frequently used)

stat function example The following displays field [2] (file permissions): print "Enter file: "; chomp ($filename = ); $mode = (stat($filename))[2]; printf "Permissions are %04o\n", $mode & 07777; # A file returning 744 permission means: #OwnerGroupOther # Read444 # Write200 # Execute100 #========================================= #744