Programming in Perl Conditional Execution, Loops, Subroutines by ekc11009

VIEWS: 18 PAGES: 8

									    Programming in Perl
     Conditional Execution,
                    Loops,
               Subroutines
 Peter Verhás
January 2002.
               Conditional execution

• if( condition ){ command(s) }
• if( condition ){ command(s) }
  else{ command(s) }
• command if condition;
• unless( condition ){ command(s) }
• unless( condition ){ command(s) }
  else{ command(s) }
• command unless condition;

• { and } MUST be used following if/unless.
                Loop constructs

• while(condition){ command(s)
  }

• do{ command(s)
  }while(condition)

• for( exp1 ; exp2 ; expr3 ){
  command(s) }
             Looping over a list

for $i (@list){}
foreach $i (@list){}
for $i (n..m) {}
for $i (n...m){}
              Make loops more complex

$i = 0;
while( $i < 7 ){
 $i ++;
 print "start $i\n";
 next if $i == 1;
                              next executes the
 redo if $i == 2;          continue part. redo does
 last if $i == 4;
 print "end $i\n";
                            not. last gets out of the
 }continue{                          loop.
 print "$i countinue\n";
 }
OUTPUT:                      You can use LABELs and
start 1                    specify the label, which loop
1 countinue
start 2                     to next, redo or last?
start 3
end 3
3 countinue
start 4
                          Subroutines

sub name { command(s) }

• Arguments are put into the global array
  @_
• You can $_[$i] or $v = shift
• Return value is return expression or
  just the last expression
• Local variables are created using
  keyword my or local
                                    local or my?

$my = 'global';
$local = 'global';

&subi;
&bubi;

sub subi {
  my $my ='my';
  local $local = 'local';   my is really local.
  &bubi;
  }
                            local is actually global, but
sub bubi {
  print "$my\n$local\n";
                            saves old value.
  }
OUTPUT:
global
local
global
global
Thank you for your kind attention.

								
To top