[plug] [Perl] sorting arrays based on scalar value - Golf anyone?
Matthew Robinson
matt at zensunni.org
Fri Nov 15 17:51:44 WST 2002
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 :)
Matt
--
print map{s&^(.)&\U\1&&&$_}split$,=$",(`$^Xdoc$,-qj`=~m&"(.*)"&)[0].$/
More information about the plug
mailing list