Prof. Alfred J Bird, Ph.D., NBCT Office – McCormack 3rd floor 607 Office Hours – Tuesday and Thursday 4:00PM to 5:15PM
What is a subroutine? How is it different from a function? Why do we use subroutines?
Subroutines in Perl have three parts: The declaration sub The name of the subroutine The name may contain a list of parameters Make the name mean something to you A block of code enclosed in curly braces { actions } The subroutine can contain any code that the main routine can contain. It can even call other subroutines.
The most common way is to just refer to it by its name followed by a set of parentheses ( ) exampleSubroutine() This can call a subroutine defined anywhere in the file. If the subroutine is defined prior to its invocation the parenthesis can be omitted. exampleSubroutine
We can also invoke the subroutine before is is defines if we let the code know it is a subroutine. We can do the by: By including the statement sub exampleSubroutine; prior to invoking it Or calling it by &exampleSubroutine; You can think of the & as a type declaration sort of like and % The first method is the more common
Arguments (parameters) can be passed into the subroutine inside an array in parenthesis following the name. Arguments are passed by reference, not by name or value Arguments are passed in the You should not use the directly but should assign it to another array ;
Subroutines return a value. It is the result of the last assignment completed. my $value = exampleSubroutine(); You can use a return statement in a subroutine As soon as the first return statement is reached, control is returned to the calling program.
There are two main types of variables. Global or package variables: Global variables are accessible anywhere in the program Lexical or local variables Only accessible within the block of code where they are defined Defined with a my statement Why do we have two types of variables? All variables are global by default!
What is a namespace? What is a package? Packages are perl files with.pm extn and are considered a separate namespace. So a package is nothing but group of related scalars,arrays,hashes and subroutines for a specific purpose. Once a package is included in a.pl file (using "use") and you want to call one of the subroutines of the package, you may have to use the scope resolution operator &package::subroutine1
What is a module? Modules are packages which have the capabilities of exporting selective subroutines/scalars/arrays/hashes of the package to the namespace of the main package itself. So for the interpreter these look as though the subroutines are part of the main package itself and so there is no need to use the scope resolution operator while calling them.
Why use PERL?\ What other languages could we use? Ruby, Python, Scripting….. TIMTOWTDI!! Other people have already done it!
In the book “Beginning Perl” Read and understand pages Read pages 215 – 229 In the book “Beginning Ubuntu Server” Read pages