#!/usr/bin/perl use v5.35.0; my %rules; my $sum = 0; while (<>) { chomp; if (/^\d+\|\d+$/) { $rules{$_} = 1; } elsif (/^\d/) { my @pages = sort { $rules{"$a|$b"} ? -1 : $rules{"$b|$a"} ? 1 : 0 } split /,/; $sum += $pages[$#pages / 2] if $_ eq join ',', @pages; } } say $sum;