in reply to return a ref to a return value (array) of another sub
First:
Returns a reference to whatever x() returns *) but functions can not return plain arrays; they returns lists or single (scalar) values, depending on how they're called (this is called context in perl).sub y { \&x(); }
update: the following is wrong, since \ forces list-context on its argument
If x() would return a list, y() would return a list of references to those values, but that's not what is happening here.
Since you're doing
y() is called in scalar (in stead of list) context. the context is propagated to the returning statement in y() - that's \&x();. That propagates the scalar context up to the my @a = (1,2,3) statement. That statement is a list assignment, and a list assignment in scalar context returns the number of values assigned.my $h = &y;
So, x() returns 3, and then you take a reference to that and return it from y() and assign it to $h.
Then you try to derefence $h as an array reference, but since $h contains a reference to a scalar, that won't work.
update: the rest is correct, though
The quickest fix would be:
sub y { [ x() ]; }
Which creates a new anynomous array containing all the values returned by x() in list context.
*) Personally I think using \&sub(); is really confusing, since \⊂ without parens returns a reference to the subroutine; generally I think it's better to never use &sub(); for calling subroutines, since ⊂ can also cause confusion - see perlsub. In essence, you only need & for taking a reference to a sub, or other special cases, and you probably should use sub(); ( or sub; ) for all "normal" cases.
|
|---|