6
SUBROUTINES

Subroutines

Embed Size (px)

Citation preview

SUBROUTINES

SUBROUTINES• Thus far we have utilized Perl predefined functions such as print and chomp. However, it is

useful to be able to create our own functions to simplify tasks.

• A subroutine is a user defined function that allows the scripter to:• Organize code

• Recycle code

• Reuse code

• Recall the scope of a function is local; Therefore we must take that into account when developing them if we want global actions.

• Good Programming: Place subroutines below your main script

DEFINING A SUBROUTINE• Perl has simplified the task to define a

function• Question: In other languages how do we

define a function/method?

• Code: sub subName

{

Block;

}

• Common Mistakes: Thinking that subroutines are like functions and placing () at the end of the definition.

• Ex.

use Cwd;

use strict;

my $currPath = getcwd;

sub homeSwitch

{

if ($currPath ne “/u/j/s/jsilver5/”)

{

$currPath = getcwd;

chdir “/u/j/s/jsilver5/”;

}

else

{

chdir $currPath;

}

}

INVOKING/CALLING A SUBROUTINE• In order to call a subroutine use an & followed by the name of the subroutine.• Code: &subName;

• Ex. • &homeSwitch;

• Common Mistakes: Thinking that subroutines are like functions and placing () at the end of the call

MAKE IT WORTHWHILE WITH A RETURN

• Each subroutine calculates a return value upon the completion of the subroutines execution.

• More often than not you will want to store the outcome of the subroutine to be used later in the script, repeatedly, etc.

• Larry thought it was wasteful and required too much effort to determine a difference between void and data type functions that he made all Perl functions return a value.

• Specifically the last calculation performed in a subroutine is stored as the return of the subroutine.

RETURN EXAMPLESQuestion: What is the return value for each of the following?

• Ex 2

my $birthStone = “Diamond”;

my $street = “Patriot”;

sub nameSmush

{

birthStone = $birthstone . “ the “ . $street;

}

print(&nameSmush);

• Ex 3

my $birthStone = “Diamond”;

my $street = “Patriot”;

sub nameSmush

{

$birthStone = $birthstone . “ the “ . $street;

print(“Your superhero name is $birthStone“);

}

$testVar = &nameSmush;

• Ex 1.

my $birthStone = “Diamond”;

my $street = “Patriot”;

sub nameSmush

{

birthStone = $birthstone . “ the “ . $street;

}

&nameSmush;