in reply to Passing variables into a subroutine
However now consider this:
And its output: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;
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
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Passing variables into a subroutine
by Freezer (Sexton) on Sep 04, 2012 at 10:26 UTC | |
by CountZero (Bishop) on Sep 04, 2012 at 16:24 UTC | |
|
Re^2: Passing variables into a subroutine
by Freezer (Sexton) on Sep 04, 2012 at 10:29 UTC | |
by CountZero (Bishop) on Sep 04, 2012 at 16:29 UTC |