80 likes | 205 Views
Programming in Perl Conditional Execution , L oops , 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) }
E N D
Programming in PerlConditional 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 usedfollowing 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; redo if $i == 2; last if $i == 4; print "end $i\n"; }continue{ print "$i countinue\n"; } OUTPUT: start 1 1 countinue start 2 start 3 end 3 3 countinue start 4 next executes the continue part. redo does not. last gets out of the loop. You can use LABELs and specify the label, which loop to next, redo or last?
Subroutines sub name { command(s) } • Arguments are put into the global array@_ • You can $_[$i]or$v = shift • Return value is return expressionor just the last expression • Local variables are created using keywordmyor local
localor my? $my = 'global'; $local = 'global'; &subi; &bubi; sub subi { my $my ='my'; local $local = 'local'; &bubi; } sub bubi { print "$my\n$local\n"; } OUTPUT: global local global global my is really local. local is actually global, but saves old value.