djna
djna

Reputation: 55937

perl strings and integers and context

I have code like this, in a much larger program

 my ($chunkCountStr, $msgid, $chunk) =  split (/:/, $msgReceived, 3);
                if ( $chunkCountStr && $msgid && $chunk ) {
                        my $chunkCount = $chunkCountStr;
                        $chunkCount += 0;
                        print "candidate :$chunkCountStr: :$chunkCount: \n";
                 # and more ...

I see this result printed:

candidate :00002: :0:

So my attempt to convert to an numeric value fails

I pull that code out into a little test program.

#!/usr/bin/perl  use strict;

my $chunkCountStr = "0002"; 
my $theThing = "1232131"; 
my $anotherThing = "zzzz";

if ( $chunkCountStr && $theThing && $anotherThing )  {
    my $chunkCount = $chunkCountStr;
    $chunkCount += 0;
    print "candidate :$chunkCountStr: :$chunkCount: \n"; 
}

And it works as expected.

candidate :0002: :2:

So what have I missed? What's the difference in the two cases?

Upvotes: 1

Views: 83

Answers (1)

djna
djna

Reputation: 55937

As both choroba and Matt Jacob implied, there was a non printable character before the first zero in the real program. In the test program we used only the expected leading 0s.

Lesson: check your data before you blame the language.

Upvotes: 2

Related Questions