Yes, it is possible to achieve your stated objective, although that is not perhaps the best way to code what you are doing.
Be aware that "terse" does not necessarily mean faster code.
Perhaps, one way:
#!/usr/bin/perl
use strict;
use warnings;
my $outs = <<'EOS';
A B C
A B D
A D E
EOS
print $outs;
my %hash;
foreach (split ' ',$outs)
{
$hash{$_}++;
}
print "Values occurring exactly twice:\n";
foreach (keys %hash)
{
print "$_\n" if ($hash{$_} ==2);
}
__END__
A B C
A B D
A D E
Values occurring exactly twice:
B
D
Another way:
#!/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;
Update: Without running deparse, I figure that
()=$outs =~ m|D|g is going to create an internal array similar to @matches, it just won't have a name in the source code. I like the 2 line version because I don't blind the reader with parens and it is both a) very easy to understand and b) will run just as quickly as the one line version. Do not mistake "terse" for "speed". It can even happen that terse is slower.
Of course, if just looking for a single letter, tr is the fastest:
if ( $outs =~ tr/D// == 2) { print "exactly 2 matches for D\n" }