mfv1984 has asked for the wisdom of the Perl Monks concerning the following question:

Hello brothers!

Suppose we have a text file called "data.txt" with some lines like this:
random data ~ random data ~ random_data
random data ~ random data ~ random_data
random data ~ random data ~ random_data
random data ~ random data ~ random_data
...

By using unix (GNU) utility ''sort'', one can sort alphabetically the lines "starting" at, say, field second or third or whatever by writing: "sort -t'~' -k2", where '-t' option receives the character which delimites the fields, and '-k' option receives the key field number for sorting (2nd in this case).

My question is: How to do that with Perl?

I've tried, without success, this: "sort {substr($a, index($a, '~')) <=> substr($b, index()} @lines;" where @lines has, obviously, the lines of "data.txt".

Any insightful idea? Thanks. Michael

  • Comment on How to sort a list of strings by an arbitrary field separator

Replies are listed 'Best First'.
Re: How to sort a list of strings by an arbitrary field separator
by moritz (Cardinal) on Aug 25, 2010 at 11:40 UTC

    Please see perlfaq4, entry "How do I sort an array by (anything)?".

    For obtaining a particular field, (split /\~/, $str, $field + 2)[$field] is useful (if $field starts counting at 0)

    Perl 6 - links to (nearly) everything that is Perl 6.

      Thanks you Moritz and Corion.
      I didn't think of looking up in the FAQ's before asking, sorry.
      This 'Schwartzian Transform' thing seems pretty nifty. Now I have something good to learn the rest of the day!

Re: How to sort a list of strings by an arbitrary field separator
by Corion (Patriarch) on Aug 25, 2010 at 11:39 UTC

    This is a FAQ. See perlfaq4, on "How do I sort an array by (anything)?".