tags:

views:

72

answers:

4

Here is the code to reproduce the problem:

sub hello { return (h => 1, n => 1); }
print join ", ", values hello();

I get the error:

Type of arg 1 to values must be hash (not subroutine entry) at - line 4, near ");" Execution of - aborted due to compilation errors.

I know I can break the call and the print on two lines:

sub hello { return (h => 1, n => 1); }
my %hash = hello();
print join ", ", values %hash;

But I don't want to do that. Is there some way to do this in one line so that I don't have to create temporary variables all the time?

A: 

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.

Platinum Azure
+8  A: 
mobrule
+1 Later than my answer, but you took the time to write an explanation.
MvanGeest
I'd use some spacing `%{{ hello() }}` reads a little better.
Axeman
+6  A: 

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.

Gilles
It's useful in real programs all the time. If you are getting returned a hash from an API and all you need are the keys or the values.
tster
@tster: that's different. Certainly `%{sub_returning_hash()}` is useful. But the question is about a sub returning a plist (i.e., a list containing successions of keys and values), and that's not common in Perl.
Gilles
@Gilles, A function which returns a hash is no different than a function which returns an array to the calling function. Plus, functions which return hashes might be uncommon in your perl, but I deal with a lot of them.
tster
+1  A: 

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.

Axeman