In day 2 part 2, rather than verify whether each game / bag has no more than the specified number of cubes of each color, we’re to determine the number (maximum) cubes of each color that we see in across any pull from each game / bag.
my %max = ( red => 12, green => 13, blue => 14);
We no longer need to set the maximum permissible count.
my %max = ( red => 0, green => 0, blue => 0);
Instead, within each row of input, accumulate the maximum count of each color seen on any pull of this game.
Perl doesn’t require initializing hashes that will be used to accumulate information and it’s idiomatic not to; but with strict/warnings, my later comparisons will fail against uninitialized hash buckets; and it’s easier to initialize them than to add logic to check whether they’re already defined.
$max{$color} = $count if $count > $max{$color};
Then in the innermost loop when processing each color, set the new max for this game / bag to that count if the count exceeds the previously-seen maximum.
$sum += $max{red} * $max{green} * $max{blue};
Finally, we’re to sum the product of RGB counts from each line (rather than the game ID as in p1).
Full Program
#!/usr/bin/perl
use warnings;
use strict;
my $sum = 0;
while (<>) {
# Split into header and list of pulls.
my ($i, $pulls) = /^Game\s+(\d+):\s+(.*)/;
my %max = ( red => 0, green => 0, blue => 0);
foreach my $pull (split(/;\s*/, $pulls)) {
foreach my $colorcount (split(/,\s*/, $pull)) {
my ($count, $color) = $colorcount =~ /^(\d+)\s+(\w+)$/
or die "unintelligible color count \"$colorcount\" " .
"on row $.\n";
$max{$color} = $count if $count > $max{$color};
} # colors
} # pulls
$sum += $max{red} * $max{green} * $max{blue};
}
print "sum is $sum\n";