meet perl, part 2 flow of control and i/o. perl statements lots of different ways to write similar...
TRANSCRIPT
Meet Perl, Part Meet Perl, Part 22
Flow of Control and I/OFlow of Control and I/O
Perl StatementsPerl 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
ConditionalsConditionals• 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.
Two kinds of conditional Two kinds of conditional operatorsoperators
• 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";
If StatementIf 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
If and ElseIf 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";}
Alternatives to the IfAlternatives 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";}
Statement ModifiersStatement 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;
LoopingLooping• 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)
For LoopFor LoopSyntax like C.
for ( $i = 0; $i < 25; $i++ ) { print "$i\n";}
for ( $i = 0; $i < @seq; $i++ ) { print "$seq[ $i ]\n";}
While loopWhile loopSyntax like C
my $total = 0;
while ( @vlist ) {
$total += $vlist[ 0 ];
shift @vlist;
}
Looping with LablesLooping with Lables• We can label some loops so we can
jump to the next iteration.• Label is just an identifier for the loopROW: 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;
Continue BlocksContinue 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++;}
Looping with LabelsLooping with Labelsmy $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
until loopuntil loop• Like a while loop, but loop as long as
the condition is false my $i = 0;
until ( $i >= 10 ) {print "$i\n";
$i++;}
Do WhileDo 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 );
Do UntilDo Until• Test-at-the-end variant of the until loop• Will always execute at least once
# This loop will print a 10my $i = 10;do {
print "$i\n";$i++;
} until ( $i >= 10 );
Foreach loopForeach loop• Made for iterating over lists
# $i takes on each value in the @colors# then the body is executedforeach $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";}
Looping Statement Looping Statement ModifiersModifiers
• Like the conditional modifierssimple-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
Looping Statement Looping Statement ModifiersModifiers
• 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;
Fun with what we knowFun 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 22641061481810
Source Code Output
Perl an I/OPerl 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, "+<file3.txt" );# open for appendingopen( OUTPUT2, ">>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;
Sending output to a fileSending output to a file• Print takes an optional output file
handle parameterprint OUTPUT "Testing $a $b $c\n";
• If no handle is given, stdout is used.
Reading Input from a fileReading Input from a file• Operator <filehandle> reads from a file.
Context determines how much you read.# read just one line$line = <INPUT>;
# read the whole file as an array of lines@lines = <INPUT>;
• Lines read from input still have eoln at the end– Can remove it with chomp (from last lesson)– chomp $line;
Reading From a FileReading 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 = <INPUT>;# While we got some input.while ( $line ) {
# print the input (newline is still on it)print $line;# read the next line$line = <INPUT>;
}
Reading from a fileReading from a file• We can shorten this with:
while ( $line = <INPUT> ) {print $line;
}
• Read reads into $_ by default• So we can write even shorter code as:
while ( <INPUT> ) {print;
}
Working with InputWorking 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
Input ExampleInput Example# open an input fileopen( INPUT, "paper.txt" );
# read each of its lineswhile ( $line = <INPUT> ) { #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;
}