Presentation is loading. Please wait.

Presentation is loading. Please wait.

Subroutines sub { –#parameters are placed – –. –return; }

Similar presentations


Presentation on theme: "Subroutines sub { –#parameters are placed – –. –return; }"— Presentation transcript:

1 Subroutines sub { –#parameters are placed in @_ – –. –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 Pass by value @a = &get_array; sub get_array{ my @a=(‘A’,’C’,’G’,’T’); return @a; }

8 Passing arrays (@a, @b) = &get_array2; #@b will be empty sub get_array2{ my @a=(‘A’,’C’,’G’,’T’); my @b=(‘X’,’Y’,’Z’); return (@a, @b); #this returns @a and @b concatenated into one array }

9 Pass by reference ($a, $b) = &get_array2; #to access the array we use @$a and @$b #the same applies to hashes except that hashes are dereferences #using %$a and %$b sub get_array2{ my @a=(‘A’,’C’,’G’,’T’); my @b=(‘X’,’Y’,’Z’); return (\@a, \@b); #this returns references (pointers) to @a and @b }


Download ppt "Subroutines sub { –#parameters are placed – –. –return; }"

Similar presentations


Ads by Google