John Doe
John Doe

Reputation: 1138

If evaluation of incremented value

I am trying to catch the case where my value is not initialized and I increment it. From what I read, $value will act based on context (if I concatenate it, it will act as empty string, if I increment it, it will act as 0).

What I don't understand is why the code above gives me : The value outside of the if: 1 and it doesn't also show: The value from if: 1

use strict;
use warnings;

my $value;

if (( $value++) == 1){
    print "The value from if: $value";
}

print "The value outside of the if: $value";

Upvotes: 1

Views: 96

Answers (1)

zdim
zdim

Reputation: 66881

You are using the post increment form of the auto-increment operator

"++" and "--" work as in C. That is, if placed before a variable, they increment or decrement the variable by one before returning the value, and if placed after, increment or decrement after returning the value.

So the value prior to increment is returned first and that is used in the statement, thus the condition is evaluated with it and found to be false. The incremented value is used the next time the variable is evaluated. With ++$value it will do what you expect. This is clearly a little tricky, to say the least.

Note that the string-vs-number magic that you mention works for increment only, not decrement operator. See the above perlop page.

Upvotes: 5

Related Questions