0

Been using perl for a while but quite often encounter this, Say, $results is a hashref and code is like below:

$results->{'Key_1'} = 'Valid_string';
if ( $results->{'Key_1'} ) {  ---> this doesn't return true
   Code to do something .....
}

If my question is clear, Can anyone explain, why this happens?

Andomar
  • 232,371
  • 49
  • 380
  • 404
NullException
  • 4,232
  • 8
  • 24
  • 44
  • 1
    It should test as true, `'Valid_string'` is a defined, multi-character string which does not solely consist of the character `'0'`. That's a true value. Either you wiped it out, or you misspelled something--*or* you have overridden your literal string to create an object and have created something that has bad stringifying code, or no failover and unexpected Boolean coercion. Then again, perhaps `$results` is a Tie, and you don't have good fetch code behind it. {breath} But if `$results` is simply a *hashref*, and the other two are just strings--it should always test true--if still set. – Axeman Feb 19 '13 at 20:05
  • Your code should work as expected as-is. This is either not the full code, or the code inside the if-statement is ambiguous to appear as a false negative. – TLP Feb 19 '13 at 22:10

2 Answers2

2

The only reason I guess is that $results is not a HASH reference or your "valid string" is in fact an integer : 0

You can test it with :

print ref $results;

It should return

HASH(0x.......)

if not, there's a problem.


Better test like this to avoid any surprise :

if (exists($results->{'Key_1'})) {
    # ...
}

See perldoc perlreftut

And perldoc -f exists :

exists EXPR

Given an expression that specifies an element of a hash, returns true if the specified element in the hash has ever been initialized, even if the corresponding value is undefined.

Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
0

That's not going to happen for that string. That could be true for other strings.

$results->{'Key_1'} = '';     # Empty string is false.
$results->{'Key_1'} = '0';    # Zero is false.

Or maybe you didn't assign a string at all

$results->{'Key_1'} = 0;      # Zero is false.
$results->{'Key_1'} = undef;  # Undef is false.

defined will return true for the empty string and zero:

if ( defined( $results->{'Key_1'} ) ) {

exists will return true for the empty string, zero and undef:

if ( exists( $results->{'Key_1'} ) ) {
ikegami
  • 367,544
  • 15
  • 269
  • 518