Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

Re: Re: Sorting a subset

by seaver (Pilgrim)
on Dec 12, 2003 at 19:38 UTC ( [id://314388]=note: print w/replies, xml ) Need Help??


in reply to Re: Sorting a subset
in thread Sorting a subset

Hey,

I like the grep substr combo, thanks for your help!

Just one more thing, what if I wanted to return the resulting array:

return sort {substr($a,1) cmp substr($b,1)} grep {substr($_,0,1) eq 'A +'} @array;

Can I do that?

Cheers
Sam

Replies are listed 'Best First'.
Re: Re: Re: Sorting a subset
by BrowserUk (Patriarch) on Dec 12, 2003 at 19:55 UTC

    It's a minor point, but as you know every string going into the sort starts with 'A', it is redundant, and much slower, to use substr within the sort block to exclude it.

    return sort grep{ substr( $_ , 0, 1 ) eq 'A' } @array;

    Will produce the same result more quickly.


    Examine what is said, not who speaks.
    "Efficiency is intelligent laziness." -David Dunham
    "Think for yourself!" - Abigail
    Hooray!

      You're probably right. I was going to point out the same thing, but then I noticed that the OP specifically did a numerical sort on the front-truncated string, which made me think that the original array might be something on the lines of:

      qw ( A100 B57 X22 A9 A12 A3 C2 )

      But who knows? ;-)

      dave

        Looking back at the OP, you're right, he did originally use <=>, but then changed to cmp in the later post to which I responded..


        Examine what is said, not who speaks.
        "Efficiency is intelligent laziness." -David Dunham
        "Think for yourself!" - Abigail
        Hooray!

Re: Re: Re: Sorting a subset
by tcf22 (Priest) on Dec 12, 2003 at 19:47 UTC
    Yep. The below code outputs the same result.
    my @array = &filter(qw(Art bob joe andy willy Andrew john Archie)); print "$_\n" for(@array); sub filter(){ return sort {substr($a,1) cmp substr($b,1)} grep {substr($_,0,1) e +q 'A'} @_; }

    - Tom

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://314388]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (6)
As of 2024-03-29 09:48 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found