To create your own Perl functions, you use the sub keyword. Your function will have a name and might accept parameters or return one or more values. After creating your function, you can use it by referencing the function name and optionally passing one or more parameters, just like any of the predefined Perl functions. For example:
$myvalue = myfunction(parameter, parameter);
Function names must follow the same rules used for variable names:
- Function names must contain only letters (a-z, A-Z), underscores (_), and numeric digits (0-9).
- The first character of a function name must be a letter (a-z, A-Z) or underscore (_).
- Function names are case-sensitive, so myfunction is not the same as MyFunction.
In Question, write your function in an <eqn> tag using syntax like the following:
sub function_name { my ($parameter_name, $parameter_name ...) = @_; function_statements return value; }where
function_nameis the name of your function.parameter_nameis the variable name of any parameter that is passed to the function.List the parameters in the order in which they will be passed to the function. For example, if your function receives x and y coordinates in that order, you would specify
my ($xvalue, $yvalue) = @_;.function_statementsare the statements in the body of the function that determine what actions are performed by the function.valueis one or more values that are returned by the function.
For example, the following function calculates the area of an ellipse, given radii of
r1andr2:sub ellipse_area { my ($r1, $r2) = @_; my $area = $r1 * $r2 * $pi; return $area; }In Question, Answer, or Solution, call the function in an <EQN> or <eqn> tag using syntax like the following:
$variable = function_name(parameter_value, parameter_value ...)where
variableis the name of the variable that should get the value returned by your function. To receive multiple values, you can specify an array or a list of variables.function_nameis the name of your function.parameter_valueis the value of any parameter that is passed to the function.
For example, the following statement calls the ellipse_area function shown above, passes two radius values to the function, and assigns a value to $key:
$key = ellipse_area(4,5);
Example Question With Function The following table summarizes an actual question. QID Name Mode Numerical Question <eqn> sub orbital_period { my ($a) = @_; my $period = decform($a**(3/2),0); return $period; } @a = (randnum(320,990,1)/10, randnum(320,990,1)/10, randnum(320,990,1)/10); '' </eqn> Use Kepler's Third Law to estimate the periods of hypothetical minor planets with the following semimajor axes:<br><br> <eqn $a[0]> AU: <_> years<br> <eqn $a[1]> AU: <_> years<br> <eqn $a[2]> AU: <_> years Answer <EQN orbital_period($a[0])> <EQN orbital_period($a[1])> <EQN orbital_period($a[2])> Display to Students 