My brother has thousands of items ids and the number of items sold in the following fashion:

    $VAR1 = {
              'sold_times' => 4,
              'item_id' => 1,
            };

    $VAR2 = {
              'sold_times' => 1,
              'item_id' => 2,
            };
    ...

This information comes from reading a Log. In Perl, this data is defined as:

    my @items_ids_sold_count_map = 
    map( { sold_times => $item_id_sold_count_map{$_}, item_id => $_,}, @items_ids);

Where: $item_id_sold_count_map is a hash and @items_ids are the keys of such hash. For reference, the hash comes from reading a Log file, as I mentioned before:

    open my $infile, "<", $file_location or die("$!: $file_location");
    while (<$infile>) {
        if (/item_id:(\d+)\s*,\s*sold/) {
            $item_id_sold_count_map{$1}++;
        }
    }
    close $infile;

I would like to present this in a ranking. The criteria would be 'sold_items', in a descending order. For example, it comes to my mind to present it in a data structure like:

    $VAR1 = { 'position' => 1, 'info' => { 'item_id' => 1, 'sold_items' => 4 },
              'position' => 2, 'info' => { 'item_id' => 2, 'sold_items' => 1 }, ... };

How can I create this data structure? While Im not looking for the "best" way exactly, there are about 500,000 items.

有帮助吗?

解决方案

It seems like you should be able to sort the array directly without having to add an additional level of hash. Something like:

my @ranked = sort { $a->{sold_items} <=> $b->{sold_items} } @items_ids_sold_count_map;

The idea here is to compare the hash fields of each element to determine the sorting order. You can switch 'a' and 'b' to go between ascending and descending sort orders.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top