Subroutines
This presentation is the property of its rightful owner.
Sponsored Links
1 / 9

Subroutines PowerPoint PPT Presentation


  • 75 Views
  • Uploaded on
  • Presentation posted in: General

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.

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.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.


- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript


Subroutines

Subroutines

  • sub <subroutine_name> {

    • #parameters are placed in @_

    • <code>

    • .

    • .

    • return;

  • }


Scope

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

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

Pass by value

$a = &add($x,$y);

sub add {

my $x=$_[0]; my $y = $_[1];

return $x+$y;

}


Pass by value1

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 value2

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

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

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

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

}

}


  • Login