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

Hi,

The Code

foreach $FD_NAME ( 1 .. 10) { if( $FD_NAME eq $CATEGORY_DATA{$FD_NAME}{'FIELD_NAME'}) { # Th +e if causing prob #Do my stuff } } print keys %CATEGORY_DATA;
The problem.
In the above code, the hash %CATEGORY_DATA is a HOH and has some values. Let us say the %CATEGORY_DATA is as follows.
%CATEGORY_DATA = ( 1 => ( FIELD_NAME => 'id' ), 4 => ( FIELD_NAME => 'name' ), );
In the "if" if I check for keys 1 & 2 everything is Ok. But when $FD_NAME is 3 ( Or any value which is NOT a key in the hash ) it creates an element in the hash. i.e when I get keys of %CATEGORY_DATA, I am getting all the numbers 1 to 10 :( Is there a way to get only keys which has some values?

Cheers !

--VC

My Home

Replies are listed 'Best First'.
Re: Automatic creation of hash elements
by kyle (Abbot) on Dec 11, 2007 at 03:56 UTC

    You can check if a key exists or is defined without creating it. You could insert that into your test like so:

    if ( exists $CATEGORY_DATA{$FD_NAME} && $FD_NAME eq $CATEGORY_DATA{$FD_NAME}{'FIELD_NAME'} )

    You could also only loop over the keys of your hash in the first place.

    foreach my $FD_NAME ( keys %CATEGORY_DATA )
Re: Automatic creation of hash elements
by NetWallah (Canon) on Dec 11, 2007 at 04:46 UTC
    You have run into Autovivification.

    To avoid that, you can do something like:

    for( grep {exists $CATEGORY_DATA{$_}} 1..10){ if( $FD_NAME eq $CATEGORY_DATA{$_}{FIELD_NAME}) { ... } }

         "As you get older three things happen. The first is your memory goes, and I can't remember the other two... " - Sir Norman Wisdom