http://www.perlmonks.org?node_id=1017270


in reply to Re^2: Golf: reverse sort /etc/passwd by UID
in thread Golf: reverse sort /etc/passwd by UID

D'oh! I did omit a couple of bits didn't I (It was (obviously) untested -- I don't have an /etc/passwd).

I tried to remove the $b=~ & $a=~ bits when I noticed that reverse was one character less -- ignoring/forgetting that $_ cannot be both at the same time :(.

I don't think the (...)[0] bits are necessary, without /g only the regex will only return one (the first) match.

This should work? (still untested):

perl -E"say sort{$b=~/:(\d+):/<=>$a=~/:(\d+):/}<>" /etc/passwd

With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^4: Golf: reverse sort /etc/passwd by UID
by thundergnat (Deacon) on Feb 05, 2013 at 20:33 UTC
    No, unfortunately that doesn't work either. A regex match in scalar context returns 1 or 0. It needs to be called in list context to return the value.
    >perl -E"print 'foo'=~/(o+)/;" oo
    >perl -E"print scalar 'foo'=~/(o+)/;" 1
Re^4: Golf: reverse sort /etc/passwd by UID
by Tommy (Chaplain) on Feb 05, 2013 at 20:26 UTC

    No, no. It does work (tested and confirmed). See my reply to thundergnat.

    NOTE- remember you have to omit the typos though, as I already pointed out. So far, the winner remains:

    UPDATE: thundergnat is right that the code below DOESN'T work as intended

    perl -e 'print reverse sort{/(:\d+:)/<=>/(:\d+:)/}<>' /etc/passwd

    Tommy
    A mistake can be valuable or costly, depending on how faithfully you pursue correction

      No, no. It doesn't work (tested and confirmed).

      The sort block operates on the global variables $a and $b. A match without an explicit variable operates on $_. There is nothing mapping $a and $b to $_ there, so the sort block is just comparing 0 to 0 and leaving the order alone. The fact that /etc/password is in a "sorted" order makes it SEEM like it is working... but it isn't.

      print reverse sort{/(:\d+:)/<=>/(:\d+:)/}<DATA>; __DATA__ aaa:5: bbb:3: ccc:1: ddd:7: eee:8:
      eee:8:
      ddd:7:
      ccc:1:
      bbb:3:
      aaa:5: