I propose replacing the three lines of the OP (shown in
sub OP) with the three lines (shown in
sub TEST). The test code around them demonstrates that they produce the same result in each of the three cases of interest. The new code is about the same length and probably less efficient, but I find it much easier to understand.
use strict;
use warnings;
use Test::More;
my $y = 5;
my %Y;
my @cases = (
[[], 'no @ARGs'], # 1
[[1,2,3], 'no matches'], # undef
[[5,2,5], '2 matches'], # 2
);
plan tests=>3;
foreach my $case (@cases) {
@ARGV = @{$case->[0]};
%Y = ();
my $Y_OP = OP();
@ARGV = @{$case->[0]};
%Y = ();
my $Y_TEST = TEST();
is($Y_TEST, $Y_OP, $case->[1]);
}
sub OP {
if(@ARGV) {
foreach (@ARGV) { $Y{$y}++,next if $y eq $_; }
} else { $Y{$y}++ }
return $Y{$y};
}
sub TEST{
my $number_of_matches = grep { $_ eq $y } @ARGV;
$number_of_matches = undef if $number_of_matches == 0;
$Y{$y} = (@ARGV != 0) ? $number_of_matches : 1;
return $Y{$y};
}
OUTPUT:
1..3
ok 1 - no @ARGs
ok 2 - no matches
ok 3 - 2 matches
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: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.