On Thu, 21 Dec 2000, Alexander Farber (EED) wrote:
> Stas Bekman wrote:
> > On Wed, 20 Dec 2000, Alexander Farber (EED) wrote:
> > >
> > > sub mysort
> > > {
> > > my $param = $query -> param ('sort') || 'MHO'; # XXX global $query,
> > > # not mod_perl clean?
> > > return $a -> {$param} cmp $b -> {$param};
> > > }
> > >
> > > This subroutine is called later as:
> > >
> > > for my $href (sort mysort values %$hohref)
> > > {
> > > ...
> > > }
> >
> > Your code is better written as:
> >
> > my $param = $query->param('sort') || 'MHO';
> > for my $href (sort {$a->{$param} cmp $b->{$param}} values %$hohref) { }
>
> but isn't it the same? The anonymous sub {$a->{$param} cmp $b->{$param}}
> uses the "outside"-variable $param.
First it's not the same waste-wise. your customized sorting function is
called for every 2 items in the list to be sorted.
perl -le '@a = (1,5,8,2); print sort {print "waste"; $a <=> $b } @a'
waste
waste
waste
waste
waste
1258
Second it's not the same closure-wise. It does matter whether you use anon
sub or the named sub. See:
http://perl.apache.org/guide/perl.html#Understanding_Closures_the_Ea
> > why wasting resources...
>
> Also, assuming I would like to have a separate sorting subroutine
> mysort, since it is mopre complicated as listed above... How would
> you pass some parameters to this subroutine? Via global vars?
I'd still use anonymous sub:
my $my_sort = sub {
$a->{$param} cmp $b->{$param}
# as much code as you want
};
for my $href (sort $my_sort values %$hohref) { }
it's recompiled on every run, therefore not sticky vars.
See the link above.
Of course the simplest solution is putting the code into the package and
use/require it from your script -- no problem as well. See the guide.
_____________________________________________________________________
Stas Bekman JAm_pH -- Just Another mod_perl Hacker
http://stason.org/ mod_perl Guide http://perl.apache.org/guide
mailto:[EMAIL PROTECTED] http://apachetoday.com http://logilune.com/
http://singlesheaven.com http://perl.apache.org http://perlmonth.com/