What you're trying to do here:
sub addition($num1,$num2)
is like saying Sub Addition(num1, num2) in
VB or some such language. Those are known as formal parameters or dummy variables.
In perl, parameters are passed through a special array called @_. (There's another variable called $_, but it's a different variable. In perl, the @ and $ are part of the variable name.)
Essentially, when you call addition(2, 3), the list (2, 3) is assigned to @_.
So to get what you're looking for, the typical way to do it is:
Code:
sub addition {
my($num1, $num2) = @_;
my $answer = $num1 + $num2;
print "$answer\n";
return $answer;
}
The "my" statement places a variable in the surrounding lexical scope, which usually means the surrounding curly braces.
But you could also do this:
Code:
sub addition {
return $_[0] + $_[1];
}
Since @_ is a regular array, you can look up its values. You can even use shift, pop and splice on it.
Perl can simulate named parameters, too:
Code:
print fraction(numerator=>7, denominator=>3);
sub denominator {
my(%params) = @_;
return $params{numerator} / $params{denominator};
}
If you want to require that sub addition be called with two scalar parameters, you can specify that like so:
Code:
sub addition($$) {
# same as before
....
}
That's known as a prototype. They don't do quite what people with assumptions from other languages expect, but they are useful. They also don't guarantee that the sub is called that way, you can bypass a prototype with an ampersand before the sub name.
And exercise caution if you add them to existing code.
Further reading.