# This: foreach my $top_item ( keys %Myhash ){ if ($top_item eq $My_Value) { # do stuff } } # can be reduced to this: if ( exists $Myhash{$My_Value} ) { # do stuff } # And this: foreach $iteminitem1 (sort(keys %{$Myhash{$item}{$iteminitem}})){ if( $iteminitem1 eq 'name' && $user_number == $Myhash{$item}{$iteminitem}{$iteminitem1} ) { my $User = $iteminitem; } } # can be reduced to this: if ( exists $Myhash{$My_Value}{$iteminitem}{'name'} and $user_number == $Myhash{$My_Value}{$iteminitem}{'name'} ) { my $User = $iteminitem; } # The combined restructuring yields: if ( exists $Myhash{$My_Value} ) { foreach $iteminitem (sort(keys %{$Myhash{$item}})){ if ( exists $Myhash{$My_Value}{$iteminitem}{'name'} and $user_number == $Myhash{$My_Value}{$iteminitem}{'name'} ) { my $User = $iteminitem; } } }