[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

Re: [MacPerl] [waffle] File::Sort



At 23.19 12/19/97, Alex Satrapa wrote:
>Sorry for the waffle below... I must have woken up the wrong side of bed
>this afternoon, 'cos my brain's running a little slow and uneconomically.
>
>At 11:31 +1100 on 20/12/97, Chris Nandor wrote:
>>At 12.28 12/19/97, Brian L. Matthews wrote:
>>>You can sort of already do that:
>
>>>$r = sub { $a cmp $b };
>>>sort {&$r} @array;
>
>I got confused when reading this, in conjunction with perlref.pod... I just
>couldn't "get" what was happening from looking at the code.
>
>In perlref.pod, the part about referencing methods, it suggests using the
>form &{$r} for code references. Any time I use "&$r" in my code, MacPerl
>seems to execute the code referenced by $r.

Alex, this is not just about passing code references, but about how to use
that reference with sort().  The basic idea is that {} is used for four
things (maybe more?): as a notation for hashes ($h{$a}), as a notation for
hash references ($h = {a=>1,b=2}), as a notation for blocks of all kind,
and as a kindof separator for references.

Saying &$code is the same thing as &{$code}.  But sort() needed the extra
{} surrounding the whole thing, thus {&{$code}} or {&$code}, just like any
sub with an ampersand or parens fails with sort:

  #!perl -wl
  sub mysort {$a cmp $b};
  @a = (0..20);
  print sort @a;
  print sort mysort @a;

  #print sort mysort() @a;         # fails
  print sort {mysort()} @a;

  #print sort &mysort @a;          #fails
  print sort {&mysort} @a;

  #print sort &mysort() @a;        #fails
  print sort {&mysort()} @a;

So when using &$code or &{$code}, we most put those inside of {}, too.

Hope this helps,

--
Chris Nandor               pudge@pobox.com           http://pudge.net/
%PGPKey=('B76E72AD',[1024,'0824 090B CE73 CA10  1FF7 7F13 8180 B6B6'])
#==                    MacPerl: Power and Ease                     ==#
#==    Publishing Date: Early 1998. http://www.ptf.com/macperl/    ==#



***** Want to unsubscribe from this list?
***** Send mail with body "unsubscribe" to mac-perl-request@iis.ee.ethz.ch