Subroutines sub { –#parameters are placed – –. –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 = &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); }
Pass by = &get_array; sub get_array{ }
Passing = &get_array2; will be empty sub get_array2{ #this concatenated into one array }
Pass by reference ($a, $b) = &get_array2; #to access the array we #the same applies to hashes except that hashes are dereferences #using %$a and %$b sub get_array2{ return #this returns references (pointers) }