1 / 9

Subroutines

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.

padma
Download Presentation

Subroutines

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Subroutines • sub <subroutine_name> { • #parameters are placed in @_ • <code> • . • . • return; • }

  2. 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.

  3. 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.

  4. Pass by value $a = &add($x,$y); sub add { my $x=$_[0]; my $y = $_[1]; return $x+$y; }

  5. 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); }

  6. 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); }

  7. 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]. “ “ ; } }

  8. 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]. “ “ ; } }

  9. 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]. “ “ ; } }

More Related