开发者

Get hash keys/values on same line as the function call

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 th开发者_StackOverflow中文版e 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?


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?)


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜