Suppose we have a subroutine returning a reference
sub aspirin {
my @items = qw(some items in here);
return \@items;
}
And another subroutine taking an array reference
sub beetroot (\@) {
my $lst = shift;
print "$_\n" for @$lst;
}
I want to get the array from aspirin and feed beetroot with it. I would like to do something like (approach A)
my $L = aspirin;
beetroot $L;
But the interpreter complains, and I need to do the following instead (approach B):
my $L = aspirin;
beetroot @$L;
So my questions are:
- Why isn’t the approach A working? The argument is actually an Array reference, which is what we want;
- Is a dereference without assignment (like the one in approach B) requiring the copy of the whole list content? (I guess not, since there’s no explicit copy).
Thanks for your answers
Perl prototypes exist to modify the behaviour of the parser, which is rarely needed. This is no exception.
If “
beetroot” doesn’t have any other arguments then you should just use@_instead of an array reference.This will have the added benefit that you don’t have to work around the parser if you just want to input a list of elements.
This works on the new version, but not the version in the question.
To get it to work with the one in the question, you have to create an anonymous array. Interesting enough, this also works with the version in this answer.
If you really want “
beetroot” to work with array references.I would write it this way.
I would only write it this way if you want to use references to reduce the memory footprint of Perl, or you have other inputs to “
beetroot“.