in reply to count number of occurrences of specific character(s) in a string
Using ifs in conjunction with last and an anonymous block is just weird. An if/elsif cascade is clearer and more efficient:
sub count_separators { my $value = shift; my $delim = shift; my $set; if ($delim eq '{') { $set = '{|}'; } elsif ($delim eq '(') { $set = '(|)'; } elsif ($delim eq '"') { $set = '"'; } else { die; # Should never occur... } print 'sub { return shift =~ tr/' . $set . '//; }' . "\n"; return eval 'sub { return shift =~ tr/' . $set . '//; }'; }
If you really want to use the obscure fabricated switch statement, do it right :)
sub count_separators { my $value = shift; my $delim = shift; my $set; { $delim eq '{' and $set = '{|}' and last; $delim eq '(' and $set = '(|)' and last; $delim eq '"' and $set = '"' and last; die; # Should never occur... } print 'sub { return shift =~ tr/' . $set . '//; }' . "\n"; return eval 'sub { return shift =~ tr/' . $set . '//; }'; }
But, given that you have only hardcoded sets, even though you have several of them, bringing eval into the equation is completely unnecessary.
This is far simpler and more efficient:
sub count_separators { my $value = shift; my $delim = shift; $delim eq '{' and return $value =~ tr[{|}][]; $delim eq '(' and return $value =~ tr[(|)][]; $delim eq '"' and return $value =~ tr["][]; #"; die; }
|
|---|