Except subroutines are supposed to be reusable.
What LanX means is that a function is a subroutine. Specifically, a subroutine that returns a value (or a list of values).
In Perl, all subroutines return a value, either explicitly or implicitly, so all Perl subroutines are also functions.
So, the following 3 definitions are equivalent:
sub myfunction_long
{
my $z = $_[0] + $_[1]; # add the first 2 parameters and assign res
+ult to $z
return $z;
}
sub myfunction_medium
{
my $z = $_[0] + $_[1]; # add the first 2 parameters and assign res
+ult to $z
} # value of $z implicitly returned
sub myfunction_short
{
$_[0] + $_[1]; # add the first 2 parameters
} # result of expression implicitly returned
print myfunction_long(1, 2); # prints 3
print myfunction_medium(1, 2); # prints 3
print myfunction_short(1, 2); # prints 3
Many people are more comfortable using return even when not needed. When not used, the result of the last executed statement is the value returned.
In some programming languages, such as C, you can define either a "pure" subroutine or a function:
In some programming languages, such as C, you can define either a function or a "pure" subroutine:
int z = 0;
void myroutine(int x, y) // "void" tells the compiler that no value is
+ returned
{
z = x + y; // add the values of the 2 defined parameters and assig
+n the result to the global z
}
int myfunction(int x, y) // "int" tells the compiler that an integer v
+alue is returned
{
return(x + y); // add the values of the 2 defined parameters then
+return the result
}
Perl, however, has no such distinction.
Update: Changed order of terms in a sentence to limit scope of the adjective "pure".
|