http://qs321.pair.com?node_id=314383


in reply to Sorting a subset

Try using grep, like so:
my @array = qw(Art bob joe andy willy Andrew john Archie); foreach(sort {substr($a,1) cmp substr($b,1)} grep /^A/, @array){ print "$_\n"; } __OUTPUT__ Andrew Archie Art
Update:You could also do it using substr instead of a regex. I'm not sure which on is more efficient.
foreach(sort {substr($a,1) cmp substr($b,1)} grep {substr($_,0,1) eq ' +A'} @array)

- Tom

Replies are listed 'Best First'.
Re: Re: Sorting a subset
by seaver (Pilgrim) on Dec 12, 2003 at 19:38 UTC
    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

      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

      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

Re: Re: Sorting a subset
by Roy Johnson (Monsignor) on Dec 12, 2003 at 19:48 UTC
    The calls to substr in the sort function are misguided microoptimization. Oops. Numerical sort of the substr.

    The PerlMonk tr/// Advocate