home *** CD-ROM | disk | FTP | other *** search
/ NetNews Usenet Archive 1992 #18 / NN_1992_18.iso / spool / comp / lang / perl / 5324 < prev    next >
Encoding:
Internet Message Format  |  1992-08-14  |  1.8 KB

  1. Path: sparky!uunet!gatech!rpi!bu.edu!bu-pub.bu.edu!jdh
  2. From: jdh@bu-pub.bu.edu (Jason Heirtzler)
  3. Newsgroups: comp.lang.perl
  4. Subject: Re: perl sort bug on Irix?
  5. Message-ID: <93717@bu.edu>
  6. Date: 14 Aug 92 19:32:16 GMT
  7. References: <93641@bu.edu>
  8. Sender: news@bu.edu
  9. Organization: Boston University, Information Technology
  10. Lines: 44
  11.  
  12. In article <93641@bu.edu>, I wrote:
  13. >Perl's sort seems to behave oddly on Irix.  What I would like
  14. >to do is an inverse sort based on the length.  Is this program
  15. >correct perl (ie. not some implementation dependant thing?)
  16. >
  17. >  #!/usr/local/bin/perl --    # -*-Perl-*-
  18. >
  19. >  push( @dirs, "usr" );
  20. >  push( @dirs, "usr/bin" );
  21. >  push( @dirs, "usr/bin/X11" );
  22. >  push( @dirs, "usr/lib" );
  23. >
  24. >  @crud =  sort {length($a) < length($b);} @dirs;
  25. >
  26. >  foreach $p ( @crud ) {
  27. >      print "$p\n";
  28. >  }
  29.  
  30. Thanks to all the people who responded, and said to use:
  31.  
  32.   @crud =  sort {length($b) <=> length($a);} @dirs;
  33.  
  34. One interesting response came from pomeranz@nas.nasa.gov
  35. (Hal R. Pomeranz) who suggested:
  36.  
  37.   By the way, if @dirs or whatever you're sorting is going to be a long
  38.   list and if you were using some more CPU intensive function than
  39.   length(), you could speed up your code:
  40.  
  41.   #!/usr/local/bin/perl
  42.  
  43.   @dirs = ("usr", "usr/bin", "usr/bin/X11", "usr/lib", ... );    # whatever
  44.   grep(($lengths{$_} = length($_)), @dirs);
  45.   @crud =  sort {$lengths{$a} <=> $lengths{$b};} @dirs;
  46.   print join("\n", @crud), "\n";
  47.  
  48.   The grep() statement is a little mysterious here, but it's really just
  49.   a tight loop through the @dirs list which sets the values of an
  50.   associative array to the lengths of the strings in your list.  Then
  51.   you can compare the lengths by doing table lookups instead of
  52.   recomputing the function in the sort clause each time.  This way you
  53.   do O(n) function calls instead of O(n*log(n)).
  54.  
  55. Thanks, folks..
  56.