Pearl inserts a sorted array

Consider the data block below, how can I save a sorted array on the 3rd field and continue to click elements?

$VAR1 = [ '1111', 'http://...', 3 #this is one of the 3rd field mentioned above ]; $VARN = [ '5555', 'http://...', 0 ]; 


My code looks like this:

 my @curItem = ($item->{id}, $item->{href}, getTotal( $item->{id}) ); push @items, \@curItem; 

I found this module that looks like what I need.

Any help was appreciated.

+7
source share
3 answers

You can use this module, you just need to provide sorting:

tie @a, "Tie::Array::Sorted", sub { $_[0]->[2] <=> $_[1]->[2] };

(Or something like that ... I will need to check this. Basically, you need to sort based on the element of the array that you are passing)

Edit:. Yes, this works for your data. Just checked:

 use Tie::Array::Sorted; tie @a, "Tie::Array::Sorted", sub { $_[0]->[2] <=> $_[1]->[2] }; push @a, [ "1111", "http:// ...", 3]; push @a, [ "5555", "http:// ...", 0]; foreach $ref (@a) { print $ref . "\n"; print "@$ref \n"; } 

Outputs:

 ARRAY(0x9130888) 5555 http:// ... 0 ARRAY(0x90dd818) 1111 http:// ... 3 
+8
source

Well, push will add an item to the end of the list, no matter what. This is a stack operation. I would say that you would probably be better off using a different data structure, such as a hash, and then only sort by key or value when necessary. Without the details of what you're trying to write, it's hard to say.

Otherwise, you will need to write a routine that looks for a list for a better place to insert, and then uses a splice to insert an element in place. This looks more like what you want to do, but I'm not sure if it will be particularly effective, since you need to search the list for the insertion point every time you want to add an element, keeping the sorted order.

+3
source

If you are adding more than one array reference for @items, first add the links, then use Shwartzian Transform to perform a single sort operation:

 @items = map $_->[1], sort { $a->[0] <=> $b->[0] } map { [ $_->[2], $_ ] } @items; 

Randal wrote a column about this: http://www.stonehenge.com/merlyn/UnixReview/col64.html

+1
source

All Articles