[lug] perl hash and array assignments in a loop

karl horlen horlenkarl at yahoo.com
Fri Nov 16 02:15:24 MST 2007


I haven't programmed perl in awhile and can't find the
answer to what should be a pretty simple operation.

I read file input line by line in a loop.  I split the
line fields out to an array called @tokens.  I know
that array is being set correctly via a test print
statement.

The problem comes in when I try to assign the array to
a hash key/variable.  After searching for a long time
it looks like perl requires that I assign an array as
a
reference to the hash key.  I believe that part is
working by debug print statements.

However when it comes time to print the array VALUES
as output, I either print the array value count or the
array reference address and never the values
contained in the array.

1) How do I output the array values contained in the
hash key in a single print statement?  Similar to how
you use 'print @tokens' for a standard array.

2) I know this will be soon on deck. How do I
individually print each hash key array value
separately using a loop?  I can handle the loop, I
just
need to know the convoluted syntax  to access the hash
key array values one by one.

My very simplified code snippet that isn't working
(stuff left out)

LOOP

  my @tokens = split(' ');

  # this works!
  #print "@tokens";

  # assign by reference
  $report{$id}{$dateinfo} = \@tokens;

  # TRY TO PRINT as an array 
  # WRONG! this prints the count of array 
  # values but not the values themselves!
  print "dateinfo is :" . @{$report{$id}{$dateinfo}} .
"\n";

  # TRY TO PRINT as a scalar
  # WRONG!  this prints the array ref not the
values!!! -> dateinfo is :ARRAY(0x8f865fc)
  print "dateinfo is :" . $report{$id}{$dateinfo} .
"\n";

END LOOP

Also.  How would I add a scalar variable that keeps a
running count of records that have the same date?

This actually works:

  $record{$id}{$dateinfo}++;

But if I assign an array to hold the field values to
that $dateinfo key as described above and then
increment a count on it, I will overwrite the array
stored in the hash key.

That means I need to go with another hash level but
I'm getting more confused with the perl syntax.  I
imagine it would look something like this:

  $record{$id}{$dateinfo}$count++;
  $record{$id}{$dateinfo}@fields;

Any Perl pros out there?



      ____________________________________________________________________________________
Never miss a thing.  Make Yahoo your home page. 
http://www.yahoo.com/r/hs



More information about the LUG mailing list