Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Misunderstanding of incrementation

Tags:

perl

I have this following Perl code:

my $val = "0";

for(my $z = 0; $z <= 14; $z++)
{
    ++$val;
    if($val == 9) {
        $val = "A";
    }
    print $val;
}

It prints:

1 2 3 4 5 6 7 8 A B 1 2 3 4 5

Yet it's supposed to continue from B to C, from C to D and so on. What is the reason for this behavior?

like image 898
Grigor Avatar asked Mar 10 '26 20:03

Grigor


2 Answers

warnings would have given you a warning message like:

Argument "B" isn't numeric in numeric eq (==)

use warnings;
use strict;

my $val = "0";

for(my $z = 0; $z <= 14; $z++)
{
    ++$val;
    if($val eq '9') {   #   <------------------
        $val = "A";
    }
    print $val;
}
like image 63
toolic Avatar answered Mar 13 '26 09:03

toolic


To quote perlop:

If you increment a variable that is numeric, or that has ever been used in a numeric context, you get a normal increment. If, however, the variable has been used in only string contexts since it was set, and has a value that is not the empty string and matches the pattern /^[a-zA-Z]*[0-9]*\z/, the increment is done as a string, preserving each character within its range, with carry... (emphasis added)

$val == 9 is a numeric context. So it prints A (you just set it), and then you get the magic increment to B (it hasn't been used in a numeric context yet), but then you hit the == (using it in a numeric context), so when you get to ++$val again B is treated as a number (0) and increments to 1.

You could use eq to make a string comparison, thus preserving the magic increment, but you could also just say:

print 1 .. 8, 'A' .. 'F';
like image 42
cjm Avatar answered Mar 13 '26 09:03

cjm