Beefy Boxes and Bandwidth Generously Provided by pair Networks
good chemistry is complicated,
and a little bit messy -LW
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??
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" }

In reply to Re: most terse regex match count by Marshall
in thread most terse regex match count by bliako

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (4)
As of 2024-04-25 06:38 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found