On May 24, Gustho said:

>Below is a sample directory listing of the mail folder
>on a Linux box, I would like to sort the same using
>the last field (ie. lward, ohara, dray) starting with
>the 2nd character (ie from ward , hara and ray) :
>
>-rw------- 1 lward   mail    0 May 24  15:43 lward
>-rw------- 1 ohara   mail 8303 May 24  15:42 ohara   
>-rw------- 1 dray    mail    0 May 24  15:42 dray  

A Schwartzian Transform (or maybe even a Guttman-Rosler Transform) seems
like a good idea here.

  @sorted =

    # get the original line back
    map { $_->[0] }

    # sort based on the string
    sort { $a->[1] cmp $b->[1] }

    # create [ line, string ] array references
    map { [ $_, /\S(\S+)$/ ] }

    # however you get the directory listing...
    qx(ls -la $dir);

A GRT would require one scan through the list first, to find the longest
username.

  @files = qx(ls -la $dir);

  $maxlen = 0;

  # loop over the usernames
  for (map /\S(\S+)$/, @files) {
    push @usernames, $_;
    $maxlen = length if $maxlen < length;
  }

Now the GRT looks like:

  @sorted =

    # get rid of leading sorting string
    map { s/^\S+\s+// }

    # sort natively -- the signature of the GRT
    sort

    # build the string of "prefix" . " " . $line
    # padding the username properly
    map { sprintf "%-${maxlen}s %s", $usernames[$_], $files[$_] }

    # the indices of the array, not the actual elements
    0 .. $#files;

I hope this sheds some light on an interesting problem.

-- 
Jeff "japhy" Pinyan      [EMAIL PROTECTED]      http://www.pobox.com/~japhy/
Are you a Monk?  http://www.perlmonks.com/     http://forums.perlguru.com/
Perl Programmer at RiskMetrics Group, Inc.     http://www.riskmetrics.com/
Acacia Fraternity, Rensselaer Chapter.         Brother #734
** I need a publisher for my book "Learning Perl's Regular Expressions" **

Reply via email to