Perl is a flexible, object-oriented language that allows you to create and
Subroutines are blocks of code that can be reused across programs. They are the same as functions or user-defined functions in Perl.
We can either define a subroutine in the same program or import it from another file using the use
, do
, or require
statements.
Generally, we can define a subroutine by following the syntax below:
# Function/Subroutine definition
sub subroutine_name {
...
...
#statements the subroutine will execute
}
# Calling a subroutine
subroutine_func();
We have to write the sub
keyword before defining the subroutine in the program.
We can pass several arguments to a subroutine, such as:
The following code snippet shows how to pass an array as an argument in a subroutine.
We use the symbol ($_
) to pass single variable arguments in a subroutine, and we use the (@_
) character to pass
my $var1 = 5; my $var2 = 6; # calling subroutine with single variable parameters subroutine_variables($var1, $var2); sub subroutine_variables{ $_[0] = 6; $_[1] = 5; } print "[1] Single variable parameters var1 = $var1, var2 = $var2 \n"; sub subroutine_array { printf "@_\n"; return; } sub subroutine_list { my @list = @_; print "[3] List parameter in subroutine is: @list\n"; } $var1 = 10; @sttr1 = (1, 2, 3, 4); sub subroutine_hash{ my %hash = @_; for my $key (keys %hash) { print "[4] Key is: $key and value is: $hash{$key}\n"; } } %hash = ('Dish1', 'Soup', 'Dish2', 'Custard', 'Dish3', 'Rice'); # calling subroutine with array parameter &subroutine_array("[2] What", "are", "subroutines", "in Perl"); # calling subroutine with list parameter subroutine_list($var1, @str1); # calling subroutine with hash parameter subroutine_hash(%hash);
The code snippet above displays how to pass and print different arguments from subroutines in Perl.
From line[1]
to line[12]
, we can see that subroutine_variable
actually swaps the values of $var
and $var2
.
The subroutine_array
includes a printf
statement with the symbol (@_
) that accepts arguments as array indices in line[38].
subroutine_list
accepts the same symbol (@_
) as an array to pass arguments as parameters – it consists of a @list
variable that includes two parameters: an array (@str1
) and a scalar variable ($var
).
subroutine_hash
works when we pass a key
along with a value
as parameters into it. This subroutine includes a for each
loop that iterates and prints the key-value pair in every statement.
RELATED TAGS
CONTRIBUTOR
View all Courses