#!/usr/bin/perl use warnings; use strict; my %hash; my $name; while (){ if (/word\s(\d+)/){ $name = $1; } elsif (! /#/){ $hash{$name}++; } } for my $key (keys %hash){ print "$key $hash{$key}\n"; } __DATA__ # run1 # word 26871 # text returns text text text # run2 # word 26872 # text returns text text #run3 #### 26871 3 26872 2