[lug] perl hash and array assignments in a loop

karl horlen horlenkarl at yahoo.com
Fri Nov 16 15:46:33 MST 2007


> > 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;
> > 

> print "dateinfo is :" .join (/ /,
> @{$report{$id}{$dateinfo}});

This does NOT work.

> or 
> print "dateinfo is :";
> foreach my $item (@{$report{$id}{$dateinfo}}){
> 	print $item;
> }

This does work but you still have to traverse the
items one by one.  Wish you could just give it the
array and have it print the whole thing or the join
described above would work.

> You need to access it in list mode not scalar mode.

Would anybody recommend another language for log file
analysis with complex data structures / multi
dimensional arrays?

bash doesn't seem to support the structures I want nor
does awk.  I decided to look at perl because of its
regexp capabilities but all of the reference
dereference hokey pokey seems to confuse the matter
and make programs hard to read.

Is python better than this?

Sorry if I've offended any perl lifers out there.



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



More information about the LUG mailing list