in reply to Problem in using 'ëxists" function to see if a key exists for a hash

First, your post is extremely difficult to read. It looks like you're missing the </code> tags. I tried reformatting your code and output, which I added at the end of this post.

It looks like you're iterating over the keys of your hash, but not using the keys to look for anything in the array. I think you might need to change the following line:

if(exists $orgin{$val})

to be the following:

if(exists $orgin{$key})

Without knowing the contents of the array and hash, it will be difficult to try to help offer suggestions on what could be wrong with your code.


OP's code and output reformatted:

foreach my $key(keys %orgin) { #my $tmp_key=quotemeta "$key"; foreach my $val(@port_list) { $val=~s/\s+$//; #print "$val***********"; #my $tmp_val=quotemeta "$val"; if(exists $orgin{$val}) { #print "same key :$tmp_val\n"; next; } else { print "$val : $key Entered the else loop\n"; push @{$orgin{$val}}, "xxxx"; $count++; } } } print Dumper \%orgin;

OUTPUT: $VAR1 = { '' => 'xxxx' , ' input' => 'xxxx' , 'input' => 'ai400_INH', 'i50_TXD_p' , 'inout' => 'VIORING50', 'DVCC16', 'VPRE30', 'VCC50_p', 'VIO50_p', 'io50_MISO_p', 'io50_NCS_p', 'io50_RXD_p', 'aio33_atb_0', 'aio33_atb_3' , 'output' => 'ao400_INH_p' , ' inout' => 'xxxx' , 'inout 4:0' => 'VIO50' , ' inout 2:0' => 'xxxx' , ' output' => 'xxxx' , ' inout 4:0' => 'xxxx' };

Replies are listed 'Best First'.
Re^2: Problem in using 'ëxists" function to see if a key exists for a hash
by achs (Initiate) on Feb 17, 2016 at 08:34 UTC
    I updated my question, can anybody please help Even when I am, not using the 'exists' function instead when I am using an 'if' loop just match the array element with the key of the %orgin. The two strings are not matching. Even I print this, the array element and the hash key appears to be the same. I don't understand how to fix this.Please help
      to add a key to the hash orgin if the array element is already present in the hash as a key.

      Don't you mean not present like in your code?

      if (exists $orgin{$val}) { next; } else { print "$val : $key Entered the else loop\n"; push @{$orgin{$val}}, "xxxx"; $count++; }
      poj
        Sorry for the error in the question. If the array element is not present in the keys of the hash%orgin, add it as a key.But here it is not happenning but don't understand why.Please help me understand what is going wrong with the code