Loading ...
Sorry, an error occurred while loading the content.

Hash of an Array

Expand Messages
  • msutfin2
    Appreciated any help... I m trying to use a hash of an array to aggregate 2 values by key. My input file has a kit_number and a quantity. The quantity can be
    Message 1 of 1 , Aug 27, 2002
    • 0 Attachment
      Appreciated any help... I'm trying to use a hash of an array to
      aggregate 2 values by key. My input file has a kit_number and a
      quantity. The quantity can be either 1 or 2. For each kit_number, ADD
      1 to the appropriate element in the array. [0] for quantity 1, [1]
      for quantity 2.

      Example input file:

      kit-1 quantity: 1
      kit-1 quantity: 2
      kit-2 quantity: 1
      kit-1 quantity: 2

      So the expected output would be:

      kit-1 quantity_1 = 2, quantity_2 = 2
      kit-2 quantity_1 = 1, quantity_2 = 0

      Here's what I believe the data structure should look like..? Does
      this match my description....?

      %save = (
      kit_num => [ quan1, quan2 ]
      }

      Here's the code I have. Problem -> this only sums quantity "1" into
      the element[0] of the array. Element[1] (quantity "2"s) remains
      undefined.

      use strict;
      use Data::Dumper;

      my %save = ();
      my $kit_num = 0;
      my $quantity = 0;

      <snip>
      # I'm reading $kit_num and $quantity from
      # the input file successfully
      </snip>

      if (quantity == 1) {
      $save{$kit_no}[0] += 1;
      } elsif ($quantity == 2) {
      $save{$kit_no}[1] += 1;
      } else {
      print "Invalid quantity\n";
      }

      print Dumper (%save);

      Thanks in advance,
      Mark
    Your message has been successfully submitted and would be delivered to recipients shortly.