200 likes | 397 Views
Perl - Advanced. More Advanced Perl Functions Control Structures Filehandles Process Management. Perl Functions. Function – Sub routine Definition Keyword “sub” – Definition of a sub routine Name of the routine “subname” Block Of statements {…} sub subname { statement_1 ;
E N D
Perl - Advanced More Advanced Perl • Functions • Control Structures • Filehandles • Process Management
Perl Functions • Function – Sub routine Definition • Keyword “sub” – Definition of a sub routine • Name of the routine “subname” • Block Of statements {…} sub subname { statement_1; statement_2; statement_3; }
Invoking a User Function • We invoke a user function from within an expression by following the subroutine name with parentheses. • say_what(); or • &say_what(); • A subroutine can invoke another subroutine, and that subroutine can in turn invoke another subroutine, and so on.
Example on Arguments sub add { $sum = 0; # initialize the sum foreach $_ (@_) { $sum += $_; # add each element } return $sum; # last expression evaluated: sum of all elements } • We invoke the above function by typing add($a, $b, …) where inside the parentheses we put as many variables as we like. • The @_ variable is privateto the subroutine. This also means that a subroutine can pass arguments to another subroutine without fear of losing its own @_ variable; The nested subroutine invocation gets its own @_ in the same way.