On Feb 10, 2004, at 8:50 AM, Richard Heintze wrote:

I have an array of hashes. What function should I be
using to interrogate each array cell when I want to
know if it is occupied?

  "exists" seemed to do the job nicely. What about
"defined"?

exists() tests if the slot was ever assigned to. defined() tests if the slot contains a defined value (read: not undef). It's a subtle difference and it gets a little fuzzier inside a loop, where skipped slots will come up, as long as a later slot has been assigned to. (See code below.) For that reason, I generally want defined() when talking about arrays.


Now I am curious: how would I implement a switch
statement (er, I mean, set of if-elsif statements) for
a hetrogeneous array where some array cells contain
arrays, others integers, other hashes?

See if this give you some ideas:


#!/usr/bin/perl

use strict;
use warnings;

my @complex = ( [ 1, 2, 3 ], 405, { dogs => 200, cats => 16 } );
$complex[4] = qr/a regex/;

print "Skipped slot.\n\n" unless exists $complex[3];

foreach (@complex) {
unless (defined $_) {
print "Undefined slot.\n";
next;
}
my $type = ref($_) || "INTEGER";

if ($type eq "ARRAY") { print "Array found: ", join(", ", @$_), "\n"; }
elsif ($type eq "HASH") {
my %hash = %$_;
print "Hash Found: ",
join(", ", map { "$_ => $hash{$_}" } keys %hash), "\n"; }
elsif ($type eq "INTEGER") { print "Integer found: $_\n"; }
else { print "Unknown type: $type\n"; }
}


__END__

James


-- 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