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

前端 未结 4 1514
难免孤独
难免孤独 2021-01-15 10:21

Here is the code to reproduce the problem:

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

I get the error:

4条回答
  •  长发绾君心
    2021-01-15 10:56

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

提交回复
热议问题