Hi everyone,

  As always, we'll start with some necessary code:
    
    #!/usr/bin/perl

    use warnings;
    use strict;
    use Data::Dumper;

  Let's say I have a hash, but I don't know at compile time how many
keys it has in it:

    my %things;
    die "You have an odd number of arguments.\n" if @ARGV % 2;
    $things{shift()} = shift() while( @ARGV );

  And furthermore, I will assume that the values in the hash are boolean
(i.e. '1' (ones) or '0' (zeros)).  Now, I want to see if the WHOLE hash
is true, this being defined as every key having a value of '1'.  If even
one key has a value of '0', I want it to be false.  I decided I could do
this by counting 'true' values:

    my $num_things = keys %things;
    my $true_things = 0;

    foreach( keys %things ) {
      $true_things++ if $things{$_};
    }

    if( $true_things == $num_things ) {
      print "The \%things hash is true\n";
    } else {
      print "The \$things hash is false\n";
    }

  But ... This seems less than elegant.  Is there an easier way, perhaps
with map somehow?  I'm not very good at looking at problems and seeing
ways that map can help me.

  With this last bit of code I can check the validity of the true/false
test:

    print Dumper( \%things );

  The whole code together is here:

#!/usr/bin/perl

use warnings;
use strict;
use Data::Dumper;

my %things;
die "You have an odd number of arguments.\n" if @ARGV % 2;
$things{shift()} = shift() while( @ARGV );

my $num_things = keys %things;
my $true_things = 0;

foreach( keys %things ) {
  $true_things++ if $things{$_};
}

if( $true_things == $num_things ) {
  print "The \%things hash is true\n";
} else {
  print "The \$things hash is false\n";
}

Print Dumper( \%things );


  Now, my output looks like this:

    # things_test 1 One 1 Two 1 Three
    The %things hash is true
    $VAR1 = {
              'Three' => '1',
              'Two' => '1',
              'One' => '1'
            };

  Or ... A false one:
    
    # things_test 1 One 0 Two 1 Three
    The %things hash is false
    $VAR1 = {
              'Three' => '1',
              'Two' => '0',
              'One' => '1'
            };

Thanks in advance for any help!

--Errin

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>


Reply via email to