04 Perl

Assignment

Today is time for some Perl! It is already installed on my Xubuntu 22.04 LTS in version 5.34.0.

#!/usr/bin/perl

use strict; # pragma that turns some expressions into errors
use warnings; # Perl world recommends

# my for local variables
my $count = 0;

# iterating over lines from std input
foreach my $line (<STDIN>) {
    # remove the last char from string
    chop($line);
    # @ is for arrays; but arrays are accessed with $
    my @spl = split(',', $line);
    my @lspl = split('-', $spl[0]);
    my @rspl = split('-', $spl[1]);
    my $inter = 0;
    # the following two conditions are overlapping
    # for two equal ranges
    # that's why we use $inter as a switch
    if (int($lspl[0]) <= int($rspl[0])) {
        if ($rspl[1] <= $lspl[1]) {
            # the right range is inside the left range
            $inter = 1;
        }
    }
    if (int($lspl[0]) >= int($rspl[0])) {
        if ($lspl[1] <= $rspl[1]) {
            # the left range is inside the right range
            $inter = 1;
        }
    }
    if ($inter > 0) {
        $count += 1
    }
}

# Perl print doesn't print newline
print "$count\n";

Second part

#!/usr/bin/perl

use strict;
use warnings;

my $overlaps = 0;

foreach my $line (<STDIN>) {
    chop($line);
    my @spl = split(',', $line);
    my @lspl = split('-', $spl[0]);
    my @rspl = split('-', $spl[1]);
    # create arrays of integers from the two ranges
    my @l = (int($lspl[0])..int($lspl[1]));
    my @r = (int($rspl[0])..int($rspl[1]));
    my %intersection = ();
    # iterate over both arrays and store counts in hash
    foreach my $x (@l, @r) {
        $intersection{$x}++;
    }
    # find such keys in the hash which have counts == 2
    if (grep { $intersection{$_} == 2 } keys %intersection) {
        $overlaps += 1;
    }
}

print "$overlaps\n";

What I learned

published: 2022-12-04
last modified: 2023-01-21

https://vit.baisa.cz/notes/code/advent-of-code-2022/04/