Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things
 
PerlMonks  

Re: most terse regex match count

by Marshall (Canon)
on May 17, 2019 at 05:49 UTC ( [id://11100141]=note: print w/replies, xml ) Need Help??


in reply to most terse regex match count

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" }

Replies are listed 'Best First'.
Re^2: most terse regex match count
by holli (Abbot) on May 17, 2019 at 09:39 UTC
    Be aware that "terse" does not necessarily mean f***** code.
    SHH! Don't use the f-word here or people will start posting benchmarks.


    holli

    You can lead your users to water, but alas, you cannot drown them.
Re^2: most terse regex match count
by bliako (Monsignor) on May 17, 2019 at 10:17 UTC
     Be aware that "terse" does not necessarily mean faster code.

    Sure, I was just trying to show off to the future generations looking at the test file. tr is an interesting idea but I need to find longer strings.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11100141]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (2)
As of 2024-04-19 22:16 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found