Ramprasad wrote:
>
> Rob Dixon wrote:
> >
> >
> > Will this do?
> >
> > sort {
> >   my ($va, $vb) = map $$hash{$_}{$sortkey}, $direction eq 'a' ? ($a, $b) : ($b, 
> > $a);
> >   $sortkey eq 'uname' ? $va cmp $vb : $va <=> $vb;
> > } keys %$hash;
> >
> > Cheers,
> >
> > Rob
> >
> >
>
> Gr8 Now the code looks more neat.
> Thanks
>
> Do you think doing an explicit
>   'if($direction eq 'a') { ...} else { ...}
> Will be less expensive, because in that case the $direction is
> checked only once here It is checked in every loop. That means
> bigger the hash, heavier the code will become
>
> Can I not dynamically create my sort function , without the ifs ,  to
> suit the parameters on the fly and then use the sort function on the
> entire hash
>
> Well anyway my actual data is not very big.
>     If I have to compromise on some cpu-cycles versus the
> code-readability I will go for better code-readability.

Precisely. A dynamic subroutine would be only be more efficient
if the compilation overhead of an 'eval' is less than the total
of all the additional tests. My guess is that you'd need quite
a lot of data for that to be true, but the only way to tell for
sure is to benchmark it.

Anyway, I always say that you should start by writing code so that
works, and then only optimise it if it is running too slowly. No-one
will thank you for writing a command-line utility that runs in 50ms
instead of 150ms.

However, it is an interesting exercise, so here's my effort below.

Cheers,

Rob



my $sub = '$$hash{$a}{$sortkey} <=> $$hash{$b}{$sortkey}';
if ($direction ne 'a') {
  $sub =~ s/\$b/\$a/;
  $sub =~ s/\$a/\$b/;
}
$sub =~ s/<=>/cmp/ if $sortkey eq 'uname';
$sub = eval "sub { $sub }";

my @keys = sort $sub keys %$hash;




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to