Programming in Perl Conditional Execution Loops Subroutines Peter
Programming in Perl Conditional Execution, Loops, Subroutines Peter Verhás January 2002.
Conditional execution • if( condition ){ command(s) } else{ command(s) } • command if condition; • 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( exp 1 ; exp 2 ; expr 3 ){ 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 $in"; next if $i == 1; redo if $i == 2; last if $i == 4; print "end $in"; }continue{ print "$i countinuen"; } 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 expression or just the last expression • Local variables are created using keyword my or local
local or my? $my = 'global'; $local = 'global'; &subi; &bubi; subi { my $my ='my'; local $local = 'local'; &bubi; } sub bubi { print "$myn$localn"; } OUTPUT: global local global my is really local is actually global, but saves old value.
Thank you for your kind attention.
- Slides: 8