perlquestion
Hofmator
I'm a bit surprised by the behaviour of the following code:
<c>
use strict;
use warnings;
my %h = (1=>2, 3=>4);
sub say { print @_, $/ };
sub get_keys {
print 'called:';
if (wantarray()) {
print 'array:';
} else {
print defined wantarray() ? 'scalar' : 'void';
}
return keys %h;
}
# Output:
say sort get_keys; # get_keys
say sort get_keys(); #
say sort &get_keys; # called:array:13
say sort &get_keys(); # called:array:13
say sort @{[get_keys]}; # called:array:13
say sort @{[get_keys()]}; # called:array:13
</c>
<p>I would have expected that all these outputs would be identical. Here my guesses what went wrong. Could somebody shed some more light on it, please.
<ul>
<li>The first case somehow gets interpreted as a bareword - and use strict; doesn't complain because there is a subroutine with that name.
<li>For the second case I'm really at a loss ...
<li>The rest of the cases show various ways of making it work. I'm a bit surprised as [perldoc://perlsub] says this concerning the calling of functions
<c>
NAME(LIST); # & is optional with parentheses.
NAME LIST; # Parentheses optional if predeclared/imported.
&NAME(LIST); # Circumvent prototypes.
</c>
Therefore there shouldn't be any difference between <c>get_keys()</c> and <c>&get_keys()</c> as get_keys doesn't use prototypes.
</ul>
<p>In case it matters: <c>This is perl, v5.6.1 built for i386-linux</c>.
<p>And btw, I came across this when I tested [module://App::Ack] (Version 1.50) and tried to run <c>ack --help types</c> which doesn't display any types for me. Tracking it down, I reached the following line in <c>App::Ack::show_help_types</c>, which exhibits the behaviour of case 2 above.
<c>
for my $type ( sort( filetypes_supported() ) ) {
</c>
<!-- Node text goes above. Div tags should contain sig only -->
<div class="pmsig"><div class="pmsig-85506">
<P>-- Hofmator</P>
<p><small><i>Code written by Hofmator and posted on PerlMonks is public domain. It is provided as is with no warranties, express or implied, of any kind. Posted code may not have been tested. Use of posted code is at your own risk.</i></small></p>
</div></div>