print

Shared by: shitingting
Categories
Tags
-
Stats
views:
0
posted:
2/1/2013
language:
Unknown
pages:
37
Document Sample
scope of work template
							                            Control Structures
• Control of
  Execution
• blocks
   – for
   – foreach
   – if/elsif/else
   – while
   – until
   – unless
   – do
    Extension - Basic Perl Programming           1
                                         Blocks
A statement block is a sequence of statements
 enclosed in matching {}.

if ($age == 16) {
  print "happy birthday\n";
}




    Extension - Basic Perl Programming            2
                                   Nested blocks
Blocks may contain other blocks.

while ($age != 7) {
  if ($age < 5) {
    $age += 4;
  } else {
    if ($age < 6) {
      $age +=3;
    } else {
      $age++;
    }          # end inner if/else
  }            # end outer if/else
}              # end while block

     Extension - Basic Perl Programming            3
                     Plain block
It is less common, but valid, to have a plain block.
   This will become important when we talk about
   variable scoping.

{
    print "I am in a block.\n";
}

print "Now I'm outta the block.\n";


      Extension - Basic Perl Programming          4
                                          Blocks
• Statements are executed in order.
• A block may be thought of as a "single"
  statement.




     Extension - Basic Perl Programming            5
                                  What is Truth?
• In Perl, only 3 things are false:

  0
  "" (the empty string)
  undef

• Everything else is true. Memorize this.



      Extension - Basic Perl Programming           6
                                         If, else
if (test expression) {
  # true -- do this
} else {
  # false - do this instead
}




    Extension - Basic Perl Programming              7
                                If/else example
if ($name eq 'Joel') {
  print "Hi Joel!\n";
} else {
  print "You're not Joel.\n";
}




    Extension - Basic Perl Programming            8
                If/else
The whole "else {}" block is optional:
if ( test expression ) {
  # do something
}

# For example:

if ( $error == 1 ) {
  print "There was an error!\n";
}

# rest of program...

     Extension - Basic Perl Programming   9
        elsif (yes it's spelled that way)
if (test expression) {
  # true -- do this

} elsif (another test) {
  # true - do this instead

} elsif (yet another test) {
  # true - do this thing instead

} else {
  # default else
}

# as many elsif's as you want

     Extension - Basic Perl Programming     10
                                          If example
print "Your name? ";
chomp ($name = <STDIN>);

if ($name eq 'Fred') {
  print "Hey Fred. Long time no see.\n";
} elsif ($name eq 'Barney') {
  print "Barney, you owe me money. Pay up.\n";
} else {
  print "Nice to meet you $name.\n";
}



     Extension - Basic Perl Programming                11
   Very common Perlism with if and truth
if ($error == 1) {
  print "Found an error.\n";
}

# OR you could write it like this:

if ($error) {
  print "Found an error.\n";
}


    Extension - Basic Perl Programming     12
 More on common Perlism with if and truth
print "Your name? ";
chomp($name = <STDIN>);

# what's going on here?
if (!$name) {
  print "Error, no name given!\n";
  exit;
}

print "Hello $name.\n";

    Extension - Basic Perl Programming   13
                                          Unless
# unless is the opposite of if
print "How old are you? ";
chomp ($age = <STDIN>);
unless ($age < 18) {
  print "Go vote!\n";
  $voter++;
}

# could also use these:
if (! ($age < 18 )) { }                       # cumbersome
if ($age >= 18)     { }                       # OK


     Extension - Basic Perl Programming                      14
                                          Loops
• The code inside an if/elsif/else block is only
  executed once.
• There are many times where you want to have
  code repeated, and that is where loops come in.
• Loops let you iterate over a block of code.




     Extension - Basic Perl Programming           15
                                         while
while ( test expression ) {
 # iterate over the code in this block
 # while test expression is TRUE.
 # don't do this block at all if test
 # expression is FALSE.

  statement1;
  statement2;
} # end of while loop


    Extension - Basic Perl Programming           16
                              while examples
$count = 0;
while ($count < 10) {
    print "I have $count toes\n";
    $count++;
}




    Extension - Basic Perl Programming         17
                              while examples
$their_guess = '';
$secret      = 'xyzzy';

while ($their_guess ne $secret) {
    print "What's the secret word? ";
    chomp ($their_guess = <STDIN>);
}

print "You got it!\n";


    Extension - Basic Perl Programming         18
                                   More on while
• Note that if the test_expression is FALSE
  when the loop is reached, then the statements will
  never be executed

$age = 14;
while ($age > 21) {
  # this never gets printed
  print "You're okay to drink beer.\n";
}
print "Hello world!\n";

      Extension - Basic Perl Programming           19
                                          until
• until acts the same as while, but tests for
  FALSE.
• until is the same as "while-not".

$age = 15;
until ($age >= 21) {
   print "Can't drink legally yet!\n";
   $age++;
}

# could also do
while ( $age < 21 ) { }                           20
     Extension - Basic Perl Programming
                                           for
• For iterates over all the elements in a list.
• If you want (hopefully you won't :-), you can use
  it just like Java, C++, et al:

for (initial; test; re-init) {
     statements;
}

# which is equivalent to
initial;
while ( test ) { statements; re_init; }
      Extension - Basic Perl Programming          21
           for examples in C/Java style
for ($i = 1; $i < 10; $i++) {
  print "Hi $i\n";
}

# note: could get the same effect with:
$i = 1;
while ($i < 10) {
  print "Hi $i\n";
  $i++;
}



   Extension - Basic Perl Programming     22
                     More for in C/Java style
for ($a=1, $b=10; $a < $b; $a += 5, $b++) {
  print "A $a, B $b\n";
}

# note: could get the same effect with:
$a = 1;
$b = 10;
while ($a < $b) {
  print "A $a, B $b\n";
  $a += 5;
  $b++;
}
     Extension - Basic Perl Programming         23
                       foreach
Very useful and commonly used function that
 iterates over a list.
The list may be a literal list (1..10), an array @foo,
 hash keys (we'll see that later), etc.

@names = qw(joelg dtreder gwbush);
foreach $name (@names) {
    print "$name\n";
    # other statements, if desired;
}



      Extension - Basic Perl Programming           24
                            Foreach examples
foreach $number (1..10) {
  print "I have $number fingers\n";
}

# Sort!
@names = qw(Joel Doug George);
foreach $name (sort @names) {
  push @sorted_names, $name;
}


    Extension - Basic Perl Programming         25
                              for vs foreach
• for and foreach are identical! Use
  whichever you prefer.




    Extension - Basic Perl Programming         26
                        For/foreach example
@animals = qw(dog cat iguana);
$count = 0;

foreach $animal (@animals) {
    print "I have a $animal\n";
    $count++;
}

print "I found $count animals!\n";


    Extension - Basic Perl Programming        27
                                         $_
• Dollar underscore, a Magical Perl Thingy.
• It's the default variable for lots of things. For
  example:
   – for and foreach loops if you don't specify a
     loop iterator variable
   – print, split, chop, chomp
• It's just a scalar, like any other scalar.



    Extension - Basic Perl Programming            28
                                         More $_
foreach (1..10) {
    print $_, "\n";
}

print "Type something: ";
while (<STDIN>) {
    chomp; # chomp'ing $_
    print "I found $_\n";
}


    Extension - Basic Perl Programming             29
                Maybe you shouldn't use $_
• I recommend that you do not use $_
  – instead, name your loop variables.

• There is only one $_ in the whole program, so it
  is possible to accidentally reset/overwrite it.

• Plus, it makes the program easier to read if you
  name your variables


      Extension - Basic Perl Programming         30
                        For/foreach examples
@names = qw(joel doug igor);
foreach $name (reverse sort @names) {
  push @newnames, uc($name);
}

# see next slide for better version of this loop
foreach (@newnames) {
  print "I found $_\n";
}
# what does this print?

     Extension - Basic Perl Programming        31
                   Example again, without $_
@names = qw(joel doug igor);
foreach $name (reverse sort @names) {
  push @newnames, uc($name);
}

# better--don't use $_
foreach $newname (@newnames) {
  print "I found $newname\n";
}


    Extension - Basic Perl Programming         32
                      Sample test expression
while ( 1 ) {
  # do something
}


• Is this legal? Sane?




     Extension - Basic Perl Programming        33
                      next
• Skips the rest of the current block and
  jumps to the top of the current block for the
  next iteration

foreach $name (qw(igor fred doug)) {
    if ($name eq 'igor') {
        next;
    }
    print "I like $name\n";
}
# who don't I like?

     Extension - Basic Perl Programming     34
                       last
• Skips the rest of the block and immediately
  drops out of the block

foreach $name (qw(jim fred bob)) {
    if ($name eq 'fred') {
        last;
    }
    print "I like $name\n";
}
# what does this print?

     Extension - Basic Perl Programming   35
    Using last to prevent an infinite loop
$magic_word = 'xyzzy'; $word = '';

while (1) {
    print "Enter a word: ";
    chomp ($word = <STDIN>);
    if ($word eq $magic_word) {
        last;
    } else {
        print "Nope, try again.\n";
    }
}
    Extension - Basic Perl Programming       36
 Alternate version of secret guessing game
$magic_word = 'xyzzy';
$word       = '';

while (1) {
    print "Enter a word: ";
    chomp ($word = <STDIN>);
    last if ($word eq $magic_word);
    print "Nope, try again.\n";
}


    Extension - Basic Perl Programming   37

						
Related docs
Other docs by shitingting
Oklahoma
Views: 71  |  Downloads: 0
pg_0013
Views: 0  |  Downloads: 0
Weekly Currencies Overview 8212005
Views: 0  |  Downloads: 0
Chattot_4thMIT_1_
Views: 0  |  Downloads: 0
ihale ile ilgili döküman
Views: 69  |  Downloads: 0
Parks NC
Views: 0  |  Downloads: 0
APEX 2008 - S1P1 Allan Dawson
Views: 69  |  Downloads: 0
2012-13 FA Checklist-Fleer
Views: 792  |  Downloads: 0
F062275
Views: 0  |  Downloads: 0
Download File - Holly Lewis
Views: 0  |  Downloads: 0