using sort directly on subroutine returning list

K

Kirk Is

I've been using Perl for at least 10 years and I'm kind of surprised I
haven't run into this one before, so I want to see if I'm interpreting it
correctly...

If I have a trivial funtion returning a list

sub getarray{
return ("x","z","y");
}

then

@files = getarray();
@files = sort @files;

does 'what I expect' while trying to be "clever" and inline it

@files = sort getarray();

Doesn't...because when the first argument to sort is a subroutine,
it tries to use it as the comparison function.

On the other hand, experimentally,
@files = sort &getarray();

Works...hmm, I guess the upshot is I'm a little fast and loose
with whether I call functions with & or not and this is one of the
relatively few times it comes back to bite me...any suggestions
on the preferred method to avoid this kind of problem?
 
K

Kirk Is

Bob Walton said:
Kirk Is wrote:

In addition, you can do:
@files = sort +getarray;
which also disambiguates the call to sort (+getarray is clearly not a
subname or a block, but an expression). I'm surprised

Huh, hadn't seen the + operator like that.
@files = sort &getarray;
works, as I would think &getarray is clearly a subname. Hmmmm. Perl
must think &getarray is an expression?

Dunno.

I really love Perl and I'm probaby too old and crusty (at 30) to change my
ways and switch to another scripting type language, but I read a
description of Ruby as trying to be the language that follows the
principle of least surprise, and sometimes it's funny when Perl doesn't
quite live up to that :)
 
G

Gunnar Hjalmarsson

Bob said:
In addition, you can do:

@files = sort +getarray;

which also disambiguates the call to sort (+getarray is clearly not a
subname or a block, but an expression).

Simply surrounding the function call with parentheses works as well:

@files = sort( getarray() );
 
G

gnari

Gunnar Hjalmarsson said:
Simply surrounding the function call with parentheses works as well:

@files = sort( getarray() );

really? what perl version ?

gnari
 
G

gnari

Gunnar Hjalmarsson said:
5.8.0 on W98 and 5.8.1 on Linux.

interesting. a 5.6.1 that I had under hand failed
with this syntax. ah well, time to ditch 5.6
anyways...

gnari
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top