use warnings; use strict; my %mycorpus = ( a => " "blah title:#this is text I do not want# title:#this is text I want 2# blah title:#this is text I do not want# blah", c => "blah blah title:#this is text I do not want# title:#this is text I want 3# title:#this is text I do not want# title:#this is text I do not want# blah", ); for my $filename (sort keys %mycorpus) { my %titles; $titles{$1}++ while $mycorpus{$filename} =~ m{ ^ title:\# (.*) \# }xmg; my @once = grep { $titles{$_}==1 } sort keys %titles; die "No title found in $filename" unless @once; warn "More than one title found in $filename" if @once>1; my $title = $once[0]; print "$title\n"; } __END__ this is text I want 1 this is text I want 2 this is text I want 3