SlideShare a Scribd company logo
2
Most read
BY
SANA MATEEN
WHAT IS SUBROUTINE?
 A Perl subroutine or function is a group of statements that together performs a task.
You can divide up your code into separate subroutines. How you divide up your
code among different subroutines is up to you, but logically the division usually is
so each function performs a specific task.
 Perl uses the terms subroutine, method and function interchangeably.
 The simplest way for reusing code is building subroutines.
 They allow executing the same code in several places in your application, and they
allow it to be executed with different parameters.
 Define and Call a Subroutine
 The general form of a subroutine definition in Perl programming language is as
follows −
 sub subroutine_name
 { body of the subroutine
 }
 The typical way of calling that Perl subroutine is as follows −
 subroutine_name( list of arguments );
 Or
 &subroutine_name(earlier way);
Because Perl compiles your program before executing it, it doesn't matter where
you declare your subroutine.
#
# Main Code
# pseudo-code
..set variables
.
call sub1
.
call sub2
.
call sub3
.
exit program
sub 1
# code for sub 1
exit subroutine
sub 2
# code for sub 2
exit subroutine
sub 3
# code for sub 3
call sub 4
exit subroutine
sub 4
# code sub4
exit
PROGRAM(CODE) DESIGN USING
SUBROUTINES
-PSEUDO CODE
PASSING ARGUMENTS TO A SUBROUTINE
 You can pass various arguments to a subroutine like you do in any other programming
language and they can be accessed inside the function using the special array @_. Thus
the first argument to the function is in $_[0], the second is in $_[1], and so on.
 You can pass arrays and hashes as arguments like any scalar but passing more than
one array or hash normally causes them to lose their separate identities. So we will
use references to pass any array or hash.
 Let's try the following example, which takes a list of numbers and then prints their
average −
PASSING LISTS TO SUBROUTINES
 Because the @_ variable is an array, it can be used to supply lists to a subroutine.
However, because of the way in which Perl accepts and parses lists and arrays, it can
be difficult to extract the individual elements from @_. If you have to pass a list
along with other scalar arguments, then make list as the last argument as
shown below −
PASSING HASHES TO SUBROUTINES
 When you supply a hash to a subroutine or operator that accepts a list, then hash is
automatically translated into a list of key/value pairs. For example −
RETURNING VALUE FROM A SUBROUTINE
 You can return a value from subroutine like you do in any other programming language. If you are
not returning a value from a subroutine then whatever calculation is last performed will
automatically returns value.
 You can return arrays and hashes from the subroutine like any scalar but returning more than one
array or hash normally causes them to lose their separate identities. So we will use references to
return any array or hash from a function.
 Let's try the following example, which takes a list of numbers and then returns their average −
PRIVATE VARIABLES IN A SUBROUTINE
 By default, all variables in Perl are global variables, which means they
can be accessed from anywhere in the program. But you can
create private variables called lexical variables at any time with
the my operator.
 The my operator confines a variable to a particular region of code in
which it can be used and accessed. Outside that region, this variable
cannot be used or accessed. This region is called its scope. A lexical
scope is usually a block of code with a set of braces around it, such as
those defining the body of the subroutine or those marking the code
blocks of if, while, for, foreach, and evalstatements.
 Following is an example showing you how to define a single or multiple
private variables using my operator −
 sub somefunc {
 my $variable; # $variable is invisible outside somefunc()
 my ($another, @an_array, %a_hash); # declaring many variables at
once
 }
The following example distinguishes between global variable and private variable.
ADVANTAGES OF SUBROUTINES
 Saves typing → fewer lines of code →less likely to make a mistake
 re-usable
 if subroutine needs to be modified, can be changed in only one place
 other programs can use the same subroutine
 can be tested separately
 makes the overall structure of the program clearer

More Related Content

What's hot (20)

PDF
gRPC and Microservices
Jonathan Gomez
 
PPT
MYSQL.ppt
webhostingguy
 
PPTX
SQL - Structured query language introduction
Smriti Jain
 
PDF
How to monitor your micro-service with Prometheus?
Wojciech Barczyński
 
PPTX
Telnet presentation
travel_affair
 
PPT
UN MUNDO CENTRADO EN LA RED
lktato
 
DOCX
Beyond syllabus for web technology
Durga Bhargavi Yarrabally
 
PDF
Unit 4 rdbms study_material
gayaramesh
 
ODP
Introduction to Apache solr
Knoldus Inc.
 
PDF
Introducción a java EE 7
Carlos Camacho
 
PPTX
Spring Web MVC
zeeshanhanif
 
PPTX
Object Oriented Programming Concepts for beginners
Vibhawa Nirmal
 
PPT
3 Tier Architecture
Webx
 
PDF
Network virtualization seminar report
SKS
 
PPTX
Demilitarized Zone (DMZ) in computer networking
ssuser7319f8
 
PPTX
SQL Operators.pptx
RUBAB79
 
PPT
Arrays in php
Laiby Thomas
 
PPTX
Presentación seguridad en redes inalámbricas
Ignacio Castillo Espitia
 
PPT
Java Servlets
BG Java EE Course
 
PPT
PLSQL
Shubham Bammi
 
gRPC and Microservices
Jonathan Gomez
 
MYSQL.ppt
webhostingguy
 
SQL - Structured query language introduction
Smriti Jain
 
How to monitor your micro-service with Prometheus?
Wojciech Barczyński
 
Telnet presentation
travel_affair
 
UN MUNDO CENTRADO EN LA RED
lktato
 
Beyond syllabus for web technology
Durga Bhargavi Yarrabally
 
Unit 4 rdbms study_material
gayaramesh
 
Introduction to Apache solr
Knoldus Inc.
 
Introducción a java EE 7
Carlos Camacho
 
Spring Web MVC
zeeshanhanif
 
Object Oriented Programming Concepts for beginners
Vibhawa Nirmal
 
3 Tier Architecture
Webx
 
Network virtualization seminar report
SKS
 
Demilitarized Zone (DMZ) in computer networking
ssuser7319f8
 
SQL Operators.pptx
RUBAB79
 
Arrays in php
Laiby Thomas
 
Presentación seguridad en redes inalámbricas
Ignacio Castillo Espitia
 
Java Servlets
BG Java EE Course
 

Viewers also liked (13)

PPTX
ARM Architecture Subroutine and Flags
COMSATS Institute of Information Technology Abbottabad
 
PPTX
00 chapter07 and_08_conversion_subroutines_force_sp13
John Todora
 
PPTX
Unit 1-strings,patterns and regular expressions
sana mateen
 
PPTX
Unit 1-introduction to perl
sana mateen
 
PPTX
Unit 1-perl names values and variables
sana mateen
 
PPTX
Subroutine in 8051 microcontroller
bhadresh savani
 
PPTX
Unit 1-scalar expressions and control structures
sana mateen
 
PPTX
Unit 1-uses for scripting languages,web scripting
sana mateen
 
PPTX
Unit 1-array,lists and hashes
sana mateen
 
PPTX
Unit 1-introduction to scripts
sana mateen
 
PPTX
Stack in microprocessor 8085(presantation)
Safin Biswas
 
PPT
Stack and subroutine
Ashim Saha
 
PPTX
Role of CPU
Yong Heui Cho
 
ARM Architecture Subroutine and Flags
COMSATS Institute of Information Technology Abbottabad
 
00 chapter07 and_08_conversion_subroutines_force_sp13
John Todora
 
Unit 1-strings,patterns and regular expressions
sana mateen
 
Unit 1-introduction to perl
sana mateen
 
Unit 1-perl names values and variables
sana mateen
 
Subroutine in 8051 microcontroller
bhadresh savani
 
Unit 1-scalar expressions and control structures
sana mateen
 
Unit 1-uses for scripting languages,web scripting
sana mateen
 
Unit 1-array,lists and hashes
sana mateen
 
Unit 1-introduction to scripts
sana mateen
 
Stack in microprocessor 8085(presantation)
Safin Biswas
 
Stack and subroutine
Ashim Saha
 
Role of CPU
Yong Heui Cho
 
Ad

Similar to Unit 1-subroutines in perl (20)

PDF
Perl_Part1
Frank Booth
 
PDF
Perl_Part6
Frank Booth
 
PPTX
Intro to Scala
manaswinimysore
 
PPTX
Shell scripting
Mufaddal Haidermota
 
PDF
Handout # 4 functions + scopes
NUST Stuff
 
PPTX
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
PPTX
C# interview
Thomson Reuters
 
PDF
1669958779195.pdf
venud11
 
PDF
SQL Joins
Robert Rico Edited
 
PDF
SQL Joins
Robert Rico Edited
 
PDF
Test Presentation
Robert Rico Edited
 
PDF
Php, mysq lpart3
Subhasis Nayak
 
PDF
379008-rc217-functionalprogramming
Luis Atencio
 
PDF
perltut
tutorialsruby
 
PDF
perltut
tutorialsruby
 
PDF
Learning puppet chapter 2
Vishal Biyani
 
PPT
Perl Reference.ppt
AshleshaKulkarni4
 
PPTX
PL SQL.pptx in computer language in database
ironman82715
 
PPTX
PHP Course (Basic to Advance)
Coder Tech
 
PDF
newperl5
tutorialsruby
 
Perl_Part1
Frank Booth
 
Perl_Part6
Frank Booth
 
Intro to Scala
manaswinimysore
 
Shell scripting
Mufaddal Haidermota
 
Handout # 4 functions + scopes
NUST Stuff
 
04. WORKING WITH FUNCTIONS-2 (1).pptx
Manas40552
 
C# interview
Thomson Reuters
 
1669958779195.pdf
venud11
 
Test Presentation
Robert Rico Edited
 
Php, mysq lpart3
Subhasis Nayak
 
379008-rc217-functionalprogramming
Luis Atencio
 
perltut
tutorialsruby
 
perltut
tutorialsruby
 
Learning puppet chapter 2
Vishal Biyani
 
Perl Reference.ppt
AshleshaKulkarni4
 
PL SQL.pptx in computer language in database
ironman82715
 
PHP Course (Basic to Advance)
Coder Tech
 
newperl5
tutorialsruby
 
Ad

More from sana mateen (20)

PPTX
Files
sana mateen
 
PPTX
PHP Variables and scopes
sana mateen
 
PPTX
Php intro
sana mateen
 
PPTX
Php and web forms
sana mateen
 
PPTX
Mail
sana mateen
 
PPTX
Files in php
sana mateen
 
PPTX
File upload php
sana mateen
 
PPTX
Regex posix
sana mateen
 
PPTX
Encryption in php
sana mateen
 
PPTX
Authentication methods
sana mateen
 
PPTX
Xml schema
sana mateen
 
PPTX
Xml dtd
sana mateen
 
PPTX
Xml dom
sana mateen
 
PPTX
Xhtml
sana mateen
 
PPTX
Intro xml
sana mateen
 
PPTX
Dom parser
sana mateen
 
PPTX
Uses for scripting languages,web scripting in perl
sana mateen
 
PPTX
Scalar expressions and control structures in perl
sana mateen
 
PPTX
Subroutines in perl
sana mateen
 
PPTX
Strings,patterns and regular expressions in perl
sana mateen
 
PHP Variables and scopes
sana mateen
 
Php intro
sana mateen
 
Php and web forms
sana mateen
 
Files in php
sana mateen
 
File upload php
sana mateen
 
Regex posix
sana mateen
 
Encryption in php
sana mateen
 
Authentication methods
sana mateen
 
Xml schema
sana mateen
 
Xml dtd
sana mateen
 
Xml dom
sana mateen
 
Intro xml
sana mateen
 
Dom parser
sana mateen
 
Uses for scripting languages,web scripting in perl
sana mateen
 
Scalar expressions and control structures in perl
sana mateen
 
Subroutines in perl
sana mateen
 
Strings,patterns and regular expressions in perl
sana mateen
 

Recently uploaded (20)

PDF
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
PPTX
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
PPTX
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
PDF
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
PPTX
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
PDF
Design Thinking basics for Engineers.pdf
CMR University
 
PPTX
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPT
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
PPTX
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
DOC
MRRS Strength and Durability of Concrete
CivilMythili
 
PPTX
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
PPTX
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
PDF
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
PPTX
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
PPTX
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PDF
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
PPTX
Introduction to Design of Machine Elements
PradeepKumarS27
 
PDF
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
PDF
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
PDF
smart lot access control system with eye
rasabzahra
 
Basic_Concepts_in_Clinical_Biochemistry_2018كيمياء_عملي.pdf
AdelLoin
 
美国电子版毕业证南卡罗莱纳大学上州分校水印成绩单USC学费发票定做学位证书编号怎么查
Taqyea
 
Evaluation and thermal analysis of shell and tube heat exchanger as per requi...
shahveer210504
 
Water Industry Process Automation & Control Monthly July 2025
Water Industry Process Automation & Control
 
Introduction to Basic Renewable Energy.pptx
examcoordinatormesu
 
Design Thinking basics for Engineers.pdf
CMR University
 
Product Development & DevelopmentLecture02.pptx
zeeshanwazir2
 
PPT2_Metal formingMECHANICALENGINEEIRNG .ppt
Praveen Kumar
 
Element 11. ELECTRICITY safety and hazards
merrandomohandas
 
MRRS Strength and Durability of Concrete
CivilMythili
 
Shinkawa Proposal to meet Vibration API670.pptx
AchmadBashori2
 
Presentation 2.pptx AI-powered home security systems Secure-by-design IoT fr...
SoundaryaBC2
 
Pressure Measurement training for engineers and Technicians
AIESOLUTIONS
 
Arduino Based Gas Leakage Detector Project
CircuitDigest
 
Worm gear strength and wear calculation as per standard VB Bhandari Databook.
shahveer210504
 
PORTFOLIO Golam Kibria Khan — architect with a passion for thoughtful design...
MasumKhan59
 
Introduction to Design of Machine Elements
PradeepKumarS27
 
International Journal of Information Technology Convergence and services (IJI...
ijitcsjournal4
 
Reasons for the succes of MENARD PRESSUREMETER.pdf
majdiamz
 
smart lot access control system with eye
rasabzahra
 

Unit 1-subroutines in perl

  • 2. WHAT IS SUBROUTINE?  A Perl subroutine or function is a group of statements that together performs a task. You can divide up your code into separate subroutines. How you divide up your code among different subroutines is up to you, but logically the division usually is so each function performs a specific task.  Perl uses the terms subroutine, method and function interchangeably.  The simplest way for reusing code is building subroutines.  They allow executing the same code in several places in your application, and they allow it to be executed with different parameters.  Define and Call a Subroutine  The general form of a subroutine definition in Perl programming language is as follows −  sub subroutine_name  { body of the subroutine  }  The typical way of calling that Perl subroutine is as follows −  subroutine_name( list of arguments );  Or  &subroutine_name(earlier way);
  • 3. Because Perl compiles your program before executing it, it doesn't matter where you declare your subroutine.
  • 4. # # Main Code # pseudo-code ..set variables . call sub1 . call sub2 . call sub3 . exit program sub 1 # code for sub 1 exit subroutine sub 2 # code for sub 2 exit subroutine sub 3 # code for sub 3 call sub 4 exit subroutine sub 4 # code sub4 exit PROGRAM(CODE) DESIGN USING SUBROUTINES -PSEUDO CODE
  • 5. PASSING ARGUMENTS TO A SUBROUTINE  You can pass various arguments to a subroutine like you do in any other programming language and they can be accessed inside the function using the special array @_. Thus the first argument to the function is in $_[0], the second is in $_[1], and so on.  You can pass arrays and hashes as arguments like any scalar but passing more than one array or hash normally causes them to lose their separate identities. So we will use references to pass any array or hash.  Let's try the following example, which takes a list of numbers and then prints their average −
  • 6. PASSING LISTS TO SUBROUTINES  Because the @_ variable is an array, it can be used to supply lists to a subroutine. However, because of the way in which Perl accepts and parses lists and arrays, it can be difficult to extract the individual elements from @_. If you have to pass a list along with other scalar arguments, then make list as the last argument as shown below −
  • 7. PASSING HASHES TO SUBROUTINES  When you supply a hash to a subroutine or operator that accepts a list, then hash is automatically translated into a list of key/value pairs. For example −
  • 8. RETURNING VALUE FROM A SUBROUTINE  You can return a value from subroutine like you do in any other programming language. If you are not returning a value from a subroutine then whatever calculation is last performed will automatically returns value.  You can return arrays and hashes from the subroutine like any scalar but returning more than one array or hash normally causes them to lose their separate identities. So we will use references to return any array or hash from a function.  Let's try the following example, which takes a list of numbers and then returns their average −
  • 9. PRIVATE VARIABLES IN A SUBROUTINE  By default, all variables in Perl are global variables, which means they can be accessed from anywhere in the program. But you can create private variables called lexical variables at any time with the my operator.  The my operator confines a variable to a particular region of code in which it can be used and accessed. Outside that region, this variable cannot be used or accessed. This region is called its scope. A lexical scope is usually a block of code with a set of braces around it, such as those defining the body of the subroutine or those marking the code blocks of if, while, for, foreach, and evalstatements.  Following is an example showing you how to define a single or multiple private variables using my operator −  sub somefunc {  my $variable; # $variable is invisible outside somefunc()  my ($another, @an_array, %a_hash); # declaring many variables at once  }
  • 10. The following example distinguishes between global variable and private variable.
  • 11. ADVANTAGES OF SUBROUTINES  Saves typing → fewer lines of code →less likely to make a mistake  re-usable  if subroutine needs to be modified, can be changed in only one place  other programs can use the same subroutine  can be tested separately  makes the overall structure of the program clearer