Advent of Code Day 2 - counting regex

Part 1

Again rather simple task, simple solution. I've seen the regex to parse the input in a lot of solutions in various languages - it's nice that even though the languages look rather different, regex unites them all (in a very weird way :-)

my $valid;
while ( my $line = <STDIN> ) {
    chomp($line);
    my ( $min, $max, $letter, $pwd ) = $line =~ /^(\d+)-(\d+) (\w): (\w+)$/;
    my $cnt =()= $pwd =~ /$letter/g;

    $valid++ if ( $min <= $cnt && $cnt <= $max );
}
say $valid;

One thing of interest is the "Saturn" operator =()=, which (using some fancy list/scalar contexts) gets the number of times the regex matches (and thus counts how often the letter occurs in the password)

Oh, and wait a minute: Since Perl 5.32 (released a few months ago) we can finally say (via chained comparisons capability )

   $valid++ if ( $min <= $cnt <= $max );

Part 2

Also not hard, but I tripped over my variable names: I copied the Part-1 solution to a new file, and kept the $min and $max names. And because I wasn't reading the spec properly, I thought we have to count how often the letter occurs in the range defined by min and max. So I got a wrong result and lost a few minutes...

my $valid;
while ( my $line = <STDIN> ) {
    chomp($line);
    my ( $p1, $p2, $letter, $pwd ) = $line =~ /^(\d+)-(\d+) (\w): (\w+)$/;
    my @pwd = ( 'X', split( //, $pwd ) );

    my $hit = 0;
    for my $i ( $p1, $p2 ) {
        $hit++ if $pwd[$i] eq $letter;
    }
    $valid++ if $hit == 1;
}
say $valid;

Instead of fiddling with the array index $i I just padded the array with an extra value, so I could use the provided values as-is.

Oh, and here's my bug:

   for my $i ( $min .. $max ) {
        $hit++ if $pwd[$i] eq $letter;
    }

Note the .. between $min and $max. That's why I renamed the vars to $p1 and $p2.

Stats & Links