I am inserting 2-dimensional array references into my heap in Perl.
How should I define the ‘elements’ attribute when constructing my heap so that I can properly use my comparator function?
my $heap = Heap::Simple->new( order => \&byNumOrStr,
elements => [Array => 0]
);
sub byNumOrStr
{
my ( $a, $b ) = @_;
$b->[0] <=> $a->[0] #0-th element is a number.
||
$a->[1] cmp $b->[1]; #1-st element is a number
}
I keep getting back this error:
Can’t use string (“2.55”) as an ARRAY ref while “strict refs” in use … (This means I might actually have to compare my “number string” numerically)
Well, it’s likely that either
$aor$bis being passed in as a string. Try printing out this variables after the assignment.From what I can see from the documentation, when you pass
elements => [ Array => 0 ], unless the 0th item in the array is an array then you’ll only be comparing the values in the first slot of the array.This means that if 2.55 is in the array like [ 2.55, … ] then that’s what’s being passed in as
$aor$b.The
elementsentry tellsH::Show you want to derive the key. For a completely generic way, it says that you can pass[Function => $code_ref_for_key]. You could make it like this:sub first_two_slots {
my $array_ref = shift;
return [ @$array_ref[0,1] ];
}
And then with the order as specified, it would pass that array into your order and specify
Original comment left in place: (It’s not relevant to how
Heap::Simplecalls order).if
byNumOrStris called fromsortDON’T assign$aand$bin it. Those values are set bysort. If there is something coming in@_it’s probably not what you want.