Presentation is loading. Please wait.

Presentation is loading. Please wait.

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.

Similar presentations


Presentation on theme: "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."— Presentation transcript:

1 Meet Perl, Part 2 Flow of Control and I/O

2 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

3 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.

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

5 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

6 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"; }

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

8 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;

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

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

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

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

13 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++; }

14 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: 0 0 1 0 1 2 0 1 2 3 0 1 2 3 4 0 1 2 3 4 5 0 1 2 3 4 5 6 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 8 0 1 2 3 4 5 6 7 8 9

15 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++; }

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

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

18 Foreach loop Made for iterating over lists # $i takes on each value in the @colors # then the body is executed foreach $i (@colors) { 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 (@flavor ) { # append " ice cream" to each array element. $_.= " ice cream"; }

19 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

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

21 Fun with what we know # make a list of values, 1 - 10. @vlist = (1..10); # An obvious way to print them out. for ( $i = 0; $i < @vlist; $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 (@vlist) { # double each value if it's odd $val *= 2 unless $val % 2 == 0; } # Another way to print them out. foreach (@vlist) { print; print "\n"; } 1 2 3 4 5 6 7 8 9 10 2 6 4 10 6 14 8 18 10 Source Code Output

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

23 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.

24 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 @lines = ; Lines read from input still have eoln at the end –Can remove it with chomp (from last lesson) –chomp $line;

25 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 = ; }

26 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; }

27 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 delimiter. @words = 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

28 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 words @words = split( / +/, $line ); # print out each word on its own line. print "$_\n" foreach @words; }


Download ppt "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."

Similar presentations


Ads by Google