http://www.perlmonks.org?node_id=991506


in reply to Passing variables into a subroutine

Your prototype definition is wrong. Your definition of (@) says that your sub takes one array or list as argument, so all arguments are flattened into one list. This is the way any "normal" subroutine without prototypes works.

However now consider this:

use Modern::Perl; sub create_output (\@$) { my ($arrayref_of_lines, $entry_no_new) = @_; say "array: @{$arrayref_of_lines}"; say "scalar: $entry_no_new"; } my @array = qw/1 2 3 4/; create_output @array, 5;
And its output:
array: 1 2 3 4 scalar: 5

This is actually one of the few cases of a prototype being applied in a useful way.

The prototype (\@$) means the first argument to your sub MUST start with a @ (in other words, it must be an array), followed by a scalar. Due to the (\@) in the prototype, Perl actually takes a reference to the array and passes that as the first argument to your sub. So don't you forget to de-reference it in your sub!

It is this automagical referencing that allows you to pass one or more arrays to a subroutine without them all getting flattened in one big @_.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

My blog: Imperial Deltronics