in reply to Using 'keys' on a list

Perhaps consider this: Updated code to be perhaps more helpful...
I think an issue here that when you "say", you have to say what you want to "say"!
use strict; use warnings; use Data::Dumper; use v5.10; sub f {a=>1,b=>2} my %result = f(); #converts a a hash passed as an arry #back into a hash print Dumper \%result; print "to print just the keys of the hash:\n"; say "$_" for keys %result; # this is much faster, execution wise... # passes back a referecne to a hash that has # been already been created. sub x { my %result; $result{a}=1; #more likely way to set the results $result{b}=2; return \%result; } my $hash_ref = x(); print "to print the keys of this hash\n"; print "$_\n" for keys (%$hash_ref); print Dumper $hash_ref; __END__ $VAR1 = { 'b' => 2, 'a' => 1 }; to print just the keys of the hash: b a to print the keys of this hash a b $VAR1 = { 'a' => 1, 'b' => 2 };
PS: I did find that say for keys %{{f}}; did indeed work.
I didn't expect that result, but it does "work".
I find say "$_" for keys %{{f}}; to be easier to understand. However, Perl is gonna make a hash from the return value of f() whether or not you give it name. I prefer the above syntax.

Replies are listed 'Best First'.
Re^2: Using 'keys' on a list
by Anonymous Monk on Jun 30, 2021 at 12:11 UTC
    # this is much faster, execution wise...

    then your benchmark is very different from mine

      I don't think a benchmark makes much sense with this very small contrived example. Most of the hashes I work with have a lot more than 2 keys! In general passing back a single thing (ref to a hash) is gonna be much faster than passing back a list of key/value pairs so that the hash can be re-created by the caller. The bigger the hash is, the more apparent this speed difference is going to be. With 2 keys, there isn't a huge difference in a practical sense (impact on total application performance might not be anything of note). With say 80,000 keys, there is a lot of difference between the 2 methods of passing back an entire hash!

      Now if all you need are the keys instead of the full hash, yes, there won't be much of a difference at all. The sub could traverse the hash and make a list. Or the sub gives the caller the ref and the caller traverses the hash to make a list. The effect and performance will be about the same. Sometimes these very short snippets of code don't reflect what is going on the in overall application. The code as formulated is a rather odd idea, pass a list of key/value pairs to the sub, only to ask what the keys are? Why have to make a hash in the first place? I dunno.

        I don't think a benchmark makes much sense ... The effect and performance will be about the same.

        there you go again making claims about performance when you haven't run the benchmarks