# Thurs Sep 18 * Questions? * Feedback on homework: coming. * Conditionals, Loops, Booleans : take 1. # The IF statement if ( $ a == 7 ) { print "a is 7\n"; } # Blocks: { ... } * we don't need a ; after the block. * "my" variables defined in the block exist _only_ in the block. * inside the () is effectivly also inside the block. # "Boolean" values in perl: ("What is truth?") * (), 0, "", undefined => false * anything else => true # numeric vs string comparison operators * <, <=, >= ==, != : numbers * lt, le, eq, ne : strings # ELSE and ELSIF (yes, that's how it's spelled.) my $DEBUG = 1; # true in perl my $VERBOSE = 0; # false in if ($DEBUG){ do something here; } elsif ($VERBOSE){ or this } else { default } #ONE LINER # if the block is on one, perl let's you stick the "if" # on the end, like this: print "hi" if $DEBUG; # same as if ($DEBUG){ print "hi"; } # ------------------ discuss boolean AND, OR, NOT operators. also &&, ||, ! with tighter precedence. - logical operations - lazy evaluation - parens for grouping $a = $bar or 7; # compare these two in the debugger for various values of $bar. $a = $bar || 7; # --- looping while (expression){ # loop } # first "for" loop foreach my $loop_variable (@list){ # set $loop_variable to each item of the list in turn. # Changing it DOES change @list! } next; # skip to next loop last; # leave loop entirely # second "for" loop for (my $i=0; $i<10; $i++){ # This is just like C. } # The 2 are actually the same. And the variable is optional. for (1..10){ print "Hi.\n"; } # "range" operator 1..10 or even "a".."z". # do primes program # Common idioms foreach my $i (1..10){ # but be aware it creates an array of 10 numbers. } my @list = ('one', 'two', 'three'); while (@list){ my $word = shift @list; # do something with the $word } # or even my @list = ('one', 'two', 'three'); while (my $word = shift @list){ # when the list is empty, $word is undefined and therefore false. } # Tertiary operator ( $condition ? $if_true : $if_false ) print $alive ? "yup" : "nope"; # A single "line" can get pretty tricky. # Can you see what the perl parse does with this one? @list = split //, "Here we go."; $x = shift @list, print defined $x ? "yup, x is $x\n" : "nope\n" for 1..20;