Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

I would like to shorten this:
foreach my $key (keys %include) { if ($include{$key} eq 'yes') { $j++; } } print "$j records found\n";
I tried:
$j++ ? ($include{$key} eq 'yes') : ''; print "$j records found\n";
Please advise because it doesnt work the way i tried.

Replies are listed 'Best First'.
Re: Shorten scrip
by blokhead (Monsignor) on May 07, 2004 at 14:13 UTC
    In scalar context, grep returns the number of times its expression was true:
    my $j = grep { $_ eq 'yes' } values %include; print "$j records found\n";
    Your ternary operator was a little backwards. $j++ was getting evaluated every time, and then depending on its truth, either the comparison or the empty string was evaluated. The comparison should be the first part of the ternary operator. But if you want to do nothing if the condition fails, you shouldn't use a ternary, the following is much easier to read:
    $j++ if $include{$_} eq 'yes';

    blokhead

Re: Shorten scrip
by Zaxo (Archbishop) on May 07, 2004 at 15:24 UTC

    Or perhaps, /^yes$/ && $j++ for values %include;

    After Compline,
    Zaxo

Re: Shorten script
by b10m (Vicar) on May 07, 2004 at 14:16 UTC

    You still have to loop through the hash somehow, but you could write it a little shorter (and yes, TIMTOWTDI)

    foreach (keys %include) { $j++ if($include{$_} eq 'yes'); } print "$j records found\n";

    Or use `grep`

    Update: ... like blokhead shows :)

    --
    b10m

    All code is usually tested, but rarely trusted.
Re: Shorten script
by Art_XIV (Hermit) on May 07, 2004 at 17:42 UTC

    If all you are trying to do is get a count of the hash elements that have 'yes' values, then:

    use strict; use warnings; my %include = ( A => 'yes', B => 'no', C => 'yes', D => 'yes', E => 'no'); my $yes_count = grep /^yes$/, values %include; print "There are $yes_count elements with 'yes'\n";
    Hanlon's Razor - "Never attribute to malice that which can be adequately explained by stupidity"
      Thanks for ALL your replies!!!