home *** CD-ROM | disk | FTP | other *** search
- Path: sparky!uunet!gatech!rpi!bu.edu!bu-pub.bu.edu!jdh
- From: jdh@bu-pub.bu.edu (Jason Heirtzler)
- Newsgroups: comp.lang.perl
- Subject: Re: perl sort bug on Irix?
- Message-ID: <93717@bu.edu>
- Date: 14 Aug 92 19:32:16 GMT
- References: <93641@bu.edu>
- Sender: news@bu.edu
- Organization: Boston University, Information Technology
- Lines: 44
-
- In article <93641@bu.edu>, I wrote:
- >Perl's sort seems to behave oddly on Irix. What I would like
- >to do is an inverse sort based on the length. Is this program
- >correct perl (ie. not some implementation dependant thing?)
- >
- > #!/usr/local/bin/perl -- # -*-Perl-*-
- >
- > push( @dirs, "usr" );
- > push( @dirs, "usr/bin" );
- > push( @dirs, "usr/bin/X11" );
- > push( @dirs, "usr/lib" );
- >
- > @crud = sort {length($a) < length($b);} @dirs;
- >
- > foreach $p ( @crud ) {
- > print "$p\n";
- > }
-
- Thanks to all the people who responded, and said to use:
-
- @crud = sort {length($b) <=> length($a);} @dirs;
-
- One interesting response came from pomeranz@nas.nasa.gov
- (Hal R. Pomeranz) who suggested:
-
- By the way, if @dirs or whatever you're sorting is going to be a long
- list and if you were using some more CPU intensive function than
- length(), you could speed up your code:
-
- #!/usr/local/bin/perl
-
- @dirs = ("usr", "usr/bin", "usr/bin/X11", "usr/lib", ... ); # whatever
- grep(($lengths{$_} = length($_)), @dirs);
- @crud = sort {$lengths{$a} <=> $lengths{$b};} @dirs;
- print join("\n", @crud), "\n";
-
- The grep() statement is a little mysterious here, but it's really just
- a tight loop through the @dirs list which sets the values of an
- associative array to the lengths of the strings in your list. Then
- you can compare the lengths by doing table lookups instead of
- recomputing the function in the sort clause each time. This way you
- do O(n) function calls instead of O(n*log(n)).
-
- Thanks, folks..
-