Re: Perl comparison function for binary search



On Sun, Apr 13, 2008 at 2:38 PM, Nelson Castillo <nelsoneci@xxxxxxxxx> wrote:
Hi :-)

I wrote this binary search function. I wrote it so that I could pass
a comparison function as the last parameter. But I have to write
"sub" and I noticed that the built in sort function doesn't need it.
So I have to write:

sub { shift <=> shift}
instead of:
{$a <=> b}.

This might be a silly question, but I'd like to know if I can modify the
binary search function to receive a function similar to the one that
"sort" receives.
snip

Short answer, no, code blocks are not accessible from normal Perl.
You must use an anonymous function.

Medium answer, yes, but you must write your library code in XS.
Normal Perl can't access code blocks, but I believe you can do it in
XS, look at perlguts and perlapi for more info.

Long answer, you can use $a and $b just like the sort function does:

my_sort(sub { $a <=> $b }, @list);

sub my_sort {
my $compare = shift;
local ($a, $b);
#set $a and $b from @_ some how
my $r = $compare->();
if ($r < 0) {
} elsif ($r == 0) {
} else {
}
}

--
Chas. Owens
wonkden.net
The most important skill a programmer can have is the ability to read.
.



Relevant Pages

  • Re: Do my variables scoped to a subroutine get reconstructed every time?
    ... The reason is that some of my code blocks in the qr/// I want to ... affect lexically scoped variables in the sub. ... apply the pattern and return a token ID and lvalue data. ... I'll put it back inside the subroutine. ...
    (comp.lang.perl.misc)
  • Re: VMWARE PERL API
    ... The problem was like i had to read the config file in /etc/vmware/ ... It's not sub BEGIN but BEGIN block, ... Four specially named code blocks are executed at the beginning and at ... So you can't execute any of ...
    (perl.beginners)
  • Re: VMWARE PERL API
    ... Im trying to Build an API in perl. ... sub BEGIN { ... Four specially named code blocks are executed at the beginning and at the ... So you can’t execute any of these ...
    (perl.beginners)
  • Perl comparison function for binary search
    ... I wrote this binary search function. ... "sub" and I noticed that the built in sort function doesn't need it. ... sub {shift shift} ...
    (perl.beginners)
  • Re: C++ or VB? Thanks.
    ... End Sub ... That is much more self documenting. ... It is quite clear what code blocks ... those are closing without having to scroll or look anywhere else. ...
    (microsoft.public.dotnet.framework.aspnet)