| |||||||||
|
| |||||||||
Perl Primer - Chapter 4 - Subroutines and Functionsby Linda Naughton
Calling FunctionsUser-defined functions are called "subroutines".Don't need parens when calling (usually).
print "Hello, world!\n";
print("Hello, world!\n";) # equivalent
Usually you'll see parens for custom functions, and no parens for standard Perl functions (print, sort, die, etc.)
Declaring SubroutinesUse the sub keyword.
sub printHello
{
print "Hello, world!\n";
}
There are no function prototypes (defining parameters, etc.)
Subroutines can be declared in any order (usually put last). Return ValuesAll subroutines in Perl have a return value (though it may not be useful).By default, it is the last expression evaluated.
sub twoPlusTwo
{
2 + 2; # Return value is 4
}
This can be confusing.
sub twoPlusTwo
{
2 + 2;
print "I can add!\n"; # Return value is 1
}
So we prefer an explicit return statement.
sub twoPlusTwo
{
print "I can add!\n";
return 2+2;
}
You can also return an array or hash easily.
sub getSomeNumbers
{
@array = (1..10);
return @array; # Returns the list
}
Passing ArgumentsArguments are passed as an array. The special variable @_ stores them.
$sum = addTwoNumbers(1, 2);
sub addTwoNumbers
{
my @numberArray = @_;
my $num1 = $numberArray[0];
my $num2 = $numberArray[1];
return $num1 + $num2;
}
But remember that there's an easier way to assign an array to a list of scalar variables:
sub addTwoNumbers
{
my ($num1, $num2) = @_;
return $num1 + $num2;
}
Arrays and hashes can be passed without any special handling, but only as the last parameter. If you try to do (scalar Ð array Ð scalar) or (array Ð hash) things will get messy. For that, you need to pass by reference.
TRY IT: Creating a Subroutine Passing ReferencesReferences in Perl are like references in C++.Putting a backslash in front of a variable passes it by reference. modifyMyVar(\$var); # Passes by referenceThe reference itself is a scalar ($varP). To dereference it, put its desired type in front of the variable name (like a cast - $$varP for a scalar cast, @$varP for an array cast, etc.).
sub modifyMyVar
{
my ($varP) = @_;
$$varP = 77; # Dereferences & modifies
}
TRY IT: Passing Parameters By Reference Exit and DieExit simply exits the program.
if ($missingSomething)
{
print "Something was missing!\n";
exit;
}
Die does the same thing, but also prints the line number on which the script died. Therefore it is preferred for error messages.
if ($missingSomething)
{
die "Something was missing!";
}
|
![]()
| ||||||||