<?xml version="1.0" encoding="windows-1252"?>
<node id="832862" title="Iterating through a HoHoH ... does a particular sub-hash exist?" created="2010-04-05 13:29:41" updated="2010-04-05 13:29:41">
<type id="115">
perlquestion</type>
<author id="826783">
jedikaiti</author>
<data>
<field name="doctext">
&lt;p&gt;I have a hash, much like the one below:&lt;br /&gt;
&lt;code&gt;%cmdData = (
     'command_1' =&gt; {
          'subfields' =&gt; [],
          'description' =&gt; 'descriptive text',
          'safety' =&gt; 'SAFE'
                    },
     'command_2' =&gt; {
          'subfields' =&gt; [
               {
                  '_size' =&gt; 32,
                   'state_conversions' =&gt; [],
                   'subfield_name' =&gt; 'sub_1',
                   '_fsw_type' =&gt; 'UINT32',
               },
               {
                  '_size' =&gt; 32,
                   'state_conversions' =&gt; [],
                   'subfield_name' =&gt; 'sub_2',
                   '_fsw_type' =&gt; 'UINT32',
               },
                          ],
          'description' =&gt; 'descriptive text',
          'safety' =&gt; 'SAFE',
                    }
)&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;What I want to do is to loop through each command (key) in the hash, and do X if it has one or more subfields, and Y if it has 0 subfields. So I have a foreach loop in my code (below), with an if/else statement.&lt;/p&gt;

&lt;p&gt;Problem is, I can't get the if/else conditions right. I have tried it as below, and I have tried &lt;code&gt;if (not defined $cmdData-&gt;{$cmd}{subfields})&lt;/code&gt;. In both cases, it prints all the command names, followed by "defined".&lt;/p&gt;

&lt;code&gt;
#!/usr/bin/perl -w
use strict;
use warnings;
use Storable;

my %info;
my $cmdData = retrieve('file.pm')

foreach my $cmd ( sort { $cmdData-&gt;{$a}{pkt_target} cmp $cmdData-&gt;{$b}{pkt_target} || $a cmp $b } keys %{$cmdData}) {
	print "$cmd   ";

	if ($cmdData-&gt;{$cmd}{subfields} eq "") {
		print "undef\n";
	} else {
		print "defined\n";
	}
};&lt;/code&gt;

&lt;p&gt;Yes, I can change the hash I'm working with - sort of. I have a preprocessing script that is compiling a whole mess of hashes of the same format into one big one in a file (so it's easier to iterate through later). I can change that script to output something nicer, but I still need to know how to tell if there are subfields or not (this is how they appear in the original hashes I'm pulling from) so I can fix them.&lt;/p&gt;
&lt;p&gt;Thanks a million, Monks!&lt;/p&gt;
&lt;!-- Node text goes above. Div tags should contain sig only --&gt;
&lt;div class="pmsig"&gt;&lt;div class="pmsig-826783"&gt;
Kaiti&lt;br /&gt;
Swiss Army Nerd
&lt;/div&gt;&lt;/div&gt;</field>
</data>
</node>
