Here is the code to reproduce the problem:
sub hello { return (h => 1, n => 1); }
print join \", \", values hello();
I get the error:
I don't see the usefulness in a real program, but yes, it is possible.
print join ", ", values %{{hello()}};
Explanation: hello()
is a list; {hello()}
is a hash reference; %{{hello()}}
is a hash.
Another thing that you could do is use a toggle variable.
sub hello { return (h => 1, n => 1); }
my $toggle = 1;
print join ", ", grep { $toggle = !$toggle; } hello();
Another thing you could do is use List::Pairwise
use List::Pairwise qw<mapp>;
print join ", ", mapp { $b } hello();
I had been looking for something to process a list of name-value pairs in a "stream" and even rolled my own, but then I found this on CPAN.
I don't believe this is possible because Perl is not strongly enough typed to know what subroutines return.
As far as Perl is concerned, all subroutines simply return LISTs (or a single SCALAR). LISTs can have certain operations applied to them (indexing, slicing, etc.), but nothing that requires an ARRAY variable (like push
, pop
, shift
) or a HASH variable (including keys
, values
, delete
, exists
).
Hash assignment takes in a LIST as a parameter (which your function returns), and creates an associative hash with every odd element serving as a key to the next even element. Only after this assignment can it be called a HASH in Perl's grammar, and therefore only then will it be usable in the values
function.
You could use hash references:
sub hello { return {h => 1, n => 1}; }
print join ", ", values %{hello()};
but otherwise, no. Perl may interpret the return value of a subroutine in either scalar or list context, but there is no concept of returning a value in a hash context.
Update: this also works
sub hello { return (h => 1, n => 1); }
print join ", ", values %{{hello()}};
The inner {}
converts the output of hello()
from a list into a hash reference.
The outer %{}
dereferences the hash.
(Does %{{}}}
count as a pseudo-operator?)