90 likes | 241 Views
Subroutines. sub <subroutine_name> { #parameters are placed in @_ <code> . . return; }. Scope. You can create local variables using my . Otherwise all variables are assumed global , i.e. they can be accessed and modified by any part of the code.
E N D
Subroutines • sub <subroutine_name> { • #parameters are placed in @_ • <code> • . • . • return; • }
Scope • You can create local variables using my. • Otherwise all variables are assumed global, i.e. they can be accessed and modified by any part of the code. • Local variables are only accessible in the scope of the code.
Pass by value and pass by reference • All variables are passed by value to subroutines. This means the original variable lying outside the subroutine scope does not get changed. • You can pass arrays by reference using \. This is the same as passing the memory location of the array.
Pass by value $a = &add($x,$y); sub add { my $x=$_[0]; my $y = $_[1]; return $x+$y; }
Pass by value ($a,$b) = &sum_prod($x,$y); sub sum_prod{ my $x=$_[0]; my $y=$_[1]; $s = $x+$y; $p = $x*$y; return ($s,$p); }
Pass by value @a = &sum_prod($x,$y); #sum in $a[0], product in $a[1] sub sum_prod{ my $x=$_[0]; my $y=$_[1]; $s = $x+$y; $p = $x*$y; return ($s,$p); }
Passing arrays by value @a=(‘A’,’C’,’G’,’T’); &print_array(@a); sub print_array{ my @a = @_; for($i = 0; $i < @a; $i++) { print $a[$i]. “ “ ; } }
Passing two arrays @a=(‘A’,’C’,’G’,’T’); @b=(‘D’,’E’,’F’); &print_array(@a, @b); sub print_array{ my @a = @_; for($i = 0; $i < @a; $i++) { print $a[$i]. “ “ ; } }
Pass by reference @a=(‘A’,’C’,’G’,’T’); @b=(‘D’,’E’,’F’); &print_array(\@a, \@b); sub print_array{ my $aref = $_[0]; for($i = 0; $i < @$aref; $i++) { print $$aref[$i]. “ “ ; } }