in reply to most terse regex match count
Perhaps, one way:
Another 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
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.#!/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;
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 | |
|
Re^2: most terse regex match count
by bliako (Abbot) on May 17, 2019 at 10:17 UTC |