Hi Stuart.

This project of yours is coming along nicely!

Stuart White wrote:
> I have a hash called fouls.  Within that hash, there
> are other hashes called offensive, personal, and
> shooting.  The keys to those hashes are names, like
> Smith, Rodriguez, and Chan.  and the values to those
> names are numbers.
> I think if I wanted to access the number of offensive
> fouls Chan committed, the syntax would be this:
>
> $fouls{$offensive}{$Chan};
>
> Is that right?

Yes, as long as you have a named hash %fouls. If it
is an anonymous hash referenced by scalar $fouls, then
you want

  $fouls->{$offensive}{$Chan};

> Assuming it is, and I have a file that is collecting
> the lines that indicate fouls, then of those,
> separating the ones that indicate offensive, personal
> and shooting, and then of those the ones that indicate
> Smith, Chan and Rodriguez and then increment each
> instance.  If my backreference variable $3 was storing
> on each pass in the while loop the type of foul
> (offensive, personal or shooting) and $1 was storing
> the name (Chan, Rodrigues or Smith)

OK lets stop there. I don't think you want to do it like
that. If, as you say, you have foul type in $3 and
player name in $1 then you want to accumulate them like
this

  $fouls{$3}{$1}++;

which, if $1 eq 'Chan' and $3 eq 'offensive' would
increment the element

  $fouls{offensive}{Chan}

Which is a lot nicer as you don't then have to declare
a scalar variable for every possible player. Be
careful about upper and lower case characters though:
as far as Perl's concerned 'Chan' and 'chan' are two
different players!

> How would I print the %fouls hash out so that the
> output would be grouped by type of foul?  Here is
> an example of the output I'd like to see.
>
> Offensive fouls:
> Chan: 3
> Rodriguez: 1
> Smith: 1
>
> Personal fouls:
> Chan: 1
> Rodriguez: 4
> Smith: 1
>
> Shooting fouls:
> Chan: 1
> Rodriguez: 1
> Smith: 2
>
> would I nest foreach loops?  If so, I'm still not sure
> how I'd do that.

You'd have to look at the three subhashes separately. Try this

  foreach $type ( qw/Offensive Personal Shooting/ ) {
    printf "%s fouls\n", $type;
    my $rank = $fouls{lc $type};
    foreach my $player (keys %$rank) {
      printf "%s: %d\n", $player, $rank->{$player};
    }
  }

I hope that's clear. Note that I've pulled out a reference
to the second-level hash in $rank to simplify the inner loop.
I've also lower-cased the values for $type to make sure that
it matches the hash key.

HTH,

Rob




-- 
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]

Reply via email to