#!/usr/bin/perl use warnings; use strict; my $a = < <2>!!! 15 <4>!!! 30 HERE my @b = split("\n", $a); my @xvals = (2, 4, 6, 8); my @collection = (); my $i; my $u; for ($i=0; $i < $#b; $i++) { foreach $u (@xvals) { if ($b[$i] =~ /<$u>[^>]*<\/$u>/) { if ($b[$i + 1] =~ /<.+>([^>]*)<\/.+>/) { my $href = {$u => $1}; push(@collection, $href); last; } else { die "Error: No y-line after x-line,"; } } } } my %result = (); foreach $i (@xvals) { foreach $u (@collection) { my %hash = %{$u}; my @onehashkey = keys(%hash); my $key = $onehashkey[0]; if ($key eq $i) { $result{$key} += $hash{$key}; } } } foreach $i (sort(keys(%result))) { print "$i => $result{$i}\n"; }