- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Passing Arguments to a Subroutine in Perl
You can pass various arguments to a Perl 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 ( explained in the next chapter ) to pass an array or hash.
Let's try the following example, which takes a list of numbers and then prints their average −
Example
#!/usr/bin/perl # Function definition sub Average { # get total number of arguments passed. $n = scalar(@_); $sum = 0; foreach $item (@_) { $sum += $item; } $average = $sum / $n; print "Average for the given numbers : $average\n"; } # Function call Average(10, 20, 30);
Output
When the above program is executed, it produces the following result −
Average for the given numbers : 20
- Related Articles
- Subroutine Call Context in Perl
- Private Variables in a Subroutine in Perl
- Define and Call a Subroutine in Perl
- Returning Value from a Subroutine in Perl
- Passing Lists to Subroutines in Perl
- Passing Hashes to Subroutines in Perl
- Passing arguments to a Tkinter button command
- Passing unknown number of arguments to a function in Javascript
- Passing static methods as arguments in PHP
- What MySQL CONCAT() function returns by passing the numeric arguments?
- 8085 program with a subroutine to add ten packed BCD numbers.
- How to Define a Format in Perl?
- Passing a vector to constructor in C++
- Passing empty parameter to a method in JavaScript
- Define a Pagination in Perl

Advertisements