Using eval is perfectly fine if you aren't going to be doing lots of them, but you may run into performance problems if you are.

I did this the other day: I needed to relabel the digits in a string of [1-4]+ so that it would start "1234". I was calling this routine many times, but since there were only 24 possible transformations I could cache them to avoid repeated evals:

my %tr; sub normalise { my $s = shift; my $from = substr $s, 0, 4; my $tr = $tr{$from} ||= eval qq{ sub { tr{$from}{1234} } }; &$tr for $s; $s; }

If you are doing this many times and the character(s) you are counting may cover too many combinations to make memoization appropriate, the best general solution is probably Roy Johnson's approach:

$count = () = ($s =~ /[$search]/g)

If you specifically know that a) the $search string is always a single character, and b) that the target string is not too long then BrowserUK's xor approach:

$count = ($s ^ ($search x length $s)) =~ tr/\0/\0/
may be better.

Hugo


In reply to Re: Capturing occurrence counts via tr/// with variable interpolation by hv
in thread Capturing occurrence counts via tr/// with variable interpolation by KenW

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



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.