[plug] [Perl] sorting arrays based on scalar value - Golf anyone?

Anthony J. Breeds-Taurima tony at cantech.net.au
Mon Nov 18 10:04:47 WST 2002


On Fri, 15 Nov 2002, Matthew Robinson wrote:

> 
> 
> Carl Gherardi wrote:
> > Golf anyone?
> > 
> > I'll put up an initial score, there must be better players out there than
> > me.
> > 
> > Assuming $id is the first entry in the file, from the initial mail that
> > looked to be right.
> > 
> > sub resort(){			13
> > my($i,$o)=($_[0],$_[1]);	24
> > open(I,"<$i")or die;		19
> > @a=<I>;				07
> > close(I);				09
> > @b=sort{$b <=> $a}@a;		21
> > open(O,">$o")or die;		20
> > print O @b;				11
> > close(O);				09
> > }					01
> > 				-----------
> > 					134
> > Close enough to what I score when I play usually!
> 
> 
> How about:
> 
> sub resort{			11
> open I,$_[0];			13
> open(O,">$_[1]");		17
> print O sort{$b<=>$a}<I>	24
> }				01
> 				--
> 				66
> 
> 
> Obviously, I've dumped all of the intermediate variables.  I've also 
> lost the die's on failed opens.  I'm no longer closing the files as they 
> will be closed when the handle goes out of scope. Finally, I've removed 
> as much formatting (brackets and whitespace) as I can see.
> 
> I can lose another 5 off the score simply by renaming the subroutine to 
> a single letter :)

---
sub resort{                    11
@ARGV=shift;                   12
open O,">@_";                  13
print O sort{$b<=>$a}<>        23
}                              01
---                            --
                               60

It's golf so we can take a few liberties to trim a few characters.

Yours Tony

   Jan 22-25 2003           Linux.Conf.AU            http://linux.conf.au/
		  The Australian Linux Technical Conference!



More information about the plug mailing list