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" }
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.