Presentation is loading. Please wait.

Presentation is loading. Please wait.

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

Similar presentations


Presentation on theme: "CPTG286K Programming - Perl Chapter 9: Misc. Control Structures Chapter 10: Filehandles & File tests."— Presentation transcript:

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

2 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

3 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

4 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

5 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

6 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

7 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

8 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

9 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

10 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

11 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 }

12 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)

13 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

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

15 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"

16 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

17 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");

18 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);

19 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

20 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: $!";

21 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

22 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)

23 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


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

Similar presentations


Ads by Google