in reply to Inexplicable uninitialized value when using (?{...}) regexp construct.

Changing the $num variable to a package variable fixes the problem for me as well. Here's what seems to be happening: You can verify this by printing $num from within the regular expression. It keeps getting updated correctly, but it's not the same $num that the return statement sees. Anyway, making it a package variable with local instead of my clearly fixes it.

Also, a minor nit: An easier way to read in binary numbers left-to-right is:

m/ (?{ $num = 0; }) (?: ([10]) (?{ $num = 2*$num + $^N; }) )+ /x
i.e, shift left (which in binary multiplies by two), and carry in the new bit. This extends to any base representation (just exchange 2 for the base). You never have to know the length in advance. As a former TA for a models of computation class, I couldn't let that one slide ;)

blokhead

Replies are listed 'Best First'.
Re^2: Inexplicable uninitialized value when using (?{...}) regexp construct.
by davido (Cardinal) on Sep 28, 2004 at 21:46 UTC

    Lol, you've got to love a refresher in middle-school math. ;) Thanks.

    Taking that into consideration, and adding a built-in string validity check, here's how the working code now looks:

    use strict; use warnings; use Carp; while ( <DATA> ) { chomp; print "$_\t=>\t", bin_to_dec($_), "\n"; } sub bin_to_dec { our $num; # $num must be a global to work. local $num; # Play nice if $num is already in global use. $_[0] =~ m/ (?=^[10]+$) # Check for a valid string. (?{ $num = 0; }) (?: ([10]) (?{ $num = 2 * $num + $^N; }) )+ /x or croak "Error: $_[0] is not a pure bit string.\n"; return $num; } __DATA__ 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111

    Thanks again...


    Dave