#!/usr/bin/perl use strict; use warnings; my $outs = <<'EOS'; A B C A B D A D E EOS if ( (()=$outs =~ m|D|g)==2) { print "exactly 2 matches for D\n" } # I think better written as: my @matches = $outs =~ m|D|g; print "exactly 2 matches for D\n" if @matches ==2;