in reply to Change this example to use references...
As I'm sure you're aware, the eval_array_size() routine in your example receives the contents of @var as a list of individual arguments. There are two ways to convert this to passing @var through a reference:
You can explicitly take a reference and pass that as a scalar value:
Note I'm using "scalar" to force the sub to return the number of elements, instead of (possibly) returning the array contents.print "\@var has ", eval_array_size(\@var), " elements.\n"; sub eval_array_size { my $aref = shift; return scalar @{$aref}; }
The second way is to prototype the function. For this to work, the function has to appear before it's called:
Here, perl will require that the function's argument be an actual array (e.g. a list of items in parentheses wouldn't be acceptable) and will automatically reference the array for you. This second method is generally used for making functions that "act" like built-in commands.sub eval_array_size (\@) { my $aref = shift; return scalar @{$aref}; } print "\@var has ", eval_array_size(@var), " elements.\n";
|
|---|