perlquestion
ankitpati
<p>
The <a href="https://perldoc.perl.org/functions/keys.html">perldoc on
<code>keys</code></a> clearly states
<blockquote>
Called in list context, returns a list
consisting of all the keys of the named hash…
</blockquote>
but makes no attempt to explain why.
</p>
<p>
Googling around for an explanation also yielded no results.
</p>
<p>
Put very simply, why does
<code>
sub uniq {
my %hash = map { $_ => 1 } @_;
return keys %hash;
}
</code>
work, but
<code>
sub uniq {
return keys map { $_ => 1 } @_;
}
</code>
not?
</p>
<hr />
<p>
<strong>
Edit:
</strong>
</p>
<p>
<em>
I express my sincerest thanks to the monks for a warm welcome into the
monastery.
</em>
</p>
<p>
Following the suggestions, I tried
<code>
sub uniq {
# two pairs of braces around map
return keys %{ { map { $_ => 1 } @_ } };
}
</code>
which works perfectly fine.
</p>
<p>
However, prior to this, even before I posted the question, I experimented
with
<code>
sub uniq {
# single pair of braces around map
return keys %{ map { $_ => 1 } @_ };
}
</code>
and it did not work.
</p>
<p>
I had always believed that braces can convert a list with even number of
elements into a valid <code>HASH</code>ref, and modulo (<code>%</code>) can
convert any valid <code>HASH</code>ref into a hash.
</p>
<p>
The question now is this: if <code>map</code> just produces a list, why does
it need two pairs of braces to emit a valid <code>HASH</code>ref?
</p>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-1182586">
<a href="https://ankitpati.in" title="Ankit Pati">State.</a> <a href="https://github.com/ankitpati" title="GitHub">Science.</a> <a href="https://google.com/+AnkitPati" title="Google+">Love.</a>
</div></div>