#!/usr/bin/env perl use strict; use warnings; use v5.22; if (@ARGV !=1) { die "Usage: $0 [input-filename]"; } my $input_filename = $ARGV[0]; open my $filehandle, '<', $input_filename or die "Could not open input file $input_filename: $!"; chomp( my @input = ( <$filehandle> ) ); # Part 1 my ($horizontal, $depth); foreach (@input) { my ($direction, $distance) = split; $horizontal += $distance if ($direction eq 'forward'); $depth += $distance if ($direction eq 'down'); $depth -= $distance if ($direction eq 'up'); } say $horizontal * $depth; # Part 2 ($horizontal, $depth) = (0, 0); my $aim = 0; foreach (@input) { my ($direction, $distance) = split; if ($direction eq 'forward') { $horizontal += $distance; $depth += $aim * $distance; } $aim += $distance if ($direction eq 'down'); $aim -= $distance if ($direction eq 'up'); } say $horizontal * $depth;