Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to understand Perl sorting the result of a function

Tags:

perl

I was trying to sort the result of a function, as in sort func(); and got burned because nothing was returned. I guess Perl thought the function call was a sorting routine followed by no data.

Perldoc says the second parameter can be a subroutine name or code block. I see func() as an invocation, not a name. I don't think this is DWIMMY at all.

To further explore how this works, I wrote this:

use strict;
use warnings;

sub func {
    return qw/ c b a /;
}

my @a;

@a = sort func();
print "1. sort func():    @a\n"; 

@a = sort &func;
print "2. sort &func:     @a\n"; 

@a = sort +func();
print "3. sort +func():   @a\n"; 

@a = sort (func());
print "4. sort (func()):  @a\n"; 

@a = sort func;
print "5. sort func:      @a\n"; 

The output, no warnings were generated:

1. sort func():
2. sort &func:     a b c
3. sort +func():   a b c
4. sort (func()):  a b c
5. sort func:      func

Number 1 is the behavior that got me - no output.

I am surprised that 2 works while 1 does not. I thought they were equivalent.

I understand 3 and 4, I used 4 to fix my problem.

I'm really confused by 5, especially given there were no warnings.

Can someone explain what is the difference between 1 & 2, and why 5 outputs the name of the function?

like image 964
Bill Ruppert Avatar asked Jun 26 '13 14:06

Bill Ruppert


1 Answers

sort func() parses as sort func (), i.e., sort an empty list [()] with the routine func.

And #5 parses as sort ("func"), sort a list containing the (bareword) string func. Maybe there ought to be a warning about this, but there isn't.


Deparser output:

$ perl -MO=Deparse -e '@a1 = sort func();' -e '@a2=sort &func;' \
    -e '@a3=sort +func();' -e '@a4=sort (func());' -e '@a5=sort func;'
@a1 = (sort func ());
@a2 = sort(&func);
@a3 = sort(func());
@a4 = sort(func());
@a5 = sort('func');
-e syntax OK
like image 64
mob Avatar answered Oct 21 '22 23:10

mob