use strict; use warnings; my $prev = 0; my $total = 0; while(my $x = ){ $prev = 1 if ($x =~ /^\[Note\]$/); my $count = 0; if (($x =~ /note_values/) && $prev){ $count = $x =~ s/(note_values)/$1/g; #if more than one note_values present in a line $prev = 0; } $total = $total + $count; } print "Number of occurence: $total";