Perl Subroutine
Subroutine is collection of statements which are used to solve particular task. Subroutine is also know as method, function in other programming language. The main advantage of functions that is defining once, and it can used repeatedly. That is a way to reusability existing code.
Define Subroutine
#!/usr/bin/perl
use strict;
use warnings;
#Define Subroutine
sub message{
print ("Hello Programmer\n");
}
#Calling method
message();
&message;
Hello Programmer
Hello Programmer
Passing Values
#!/usr/bin/perl
use strict;
use warnings;
#Define Subroutine
sub info{
#Subroutine instuction
#Get parameter value
my($message) = @_;
#Display message value
print ("$message\n");
}
#Calling to method
info("Perl Code");
info("Test Data");
Perl Code
Test Data
Returning Values
#!/usr/bin/perl
use strict;
use warnings;
sub add{
my ($num1,$num2)=@_;
return $num1 + $num2;
}
sub subtract{
my ($num1,$num2)=@_;
return $num1 - $num2;
}
print("Add : ",add(30,20),"\n");
print("Sub : ",subtract(30,20),"\n");
Add : 50
Sub : 10
Define global variable
Some special case it can possible you'll are need define global variable within the function. Then you can use our word to define variable. In below example are define two global variable inside a subroutine..
#!/usr/bin/perl
package Regular;
use strict;
use warnings;
sub add{
our ($num1,$num2)=@_;
return $num1 + $num2;
}
print add(10,20),"\n";
#get the global variables
print ${Regular::num1},"\n";
print ${Regular::num2},"\n";

30
10
20
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment