brwarn has asked for the wisdom of the Perl Monks concerning the following question:

Hello Monks, I can't figure out what to do with my s/// line below to get rid of the 'uninitialized value in substitution' error that I'm getting. I looked at this earlier thread for some insight, but can't figure out how to apply it to my case. Anyway, the offending code is:
# initialize @row my @row; # for each table row, apply all the regex patterns in order to the tva +l_test column open(FILE, "< $file") || die "Can't open regex.txt: $!\n"; while(my $regex=<FILE>){ # get all tval_test columns my $sql_q = "select tval_test from cas_testbed.rtemp"; my $sthr = $dbh->prepare($sql_q); $sthr->execute; my @rex = split(/\s/,$regex); # work on each tval_test row while (@row = $sthr->fetchrow_array){ # search for $rex[0] and replace with $rex[1] s/$rex[0]/$rex[1]/ig; } # END while (@row = $sth->fetchrow_array) $sthr->finish; } # END while(my $regex=<FILE>) close FILE;

Replies are listed 'Best First'.
Re: DBI, s/// => unitinitialized value in substitution
by bellaire (Hermit) on Mar 05, 2009 at 17:07 UTC
    I don't see where @rex is being initialized. Did you mean to use $row[] instead? That would certainly explain the uninitialized value warning. Update: Actually, you're subtituting on $_, which isn't being set either. I think your code sample is incomplete!
Re: DBI, s/// => unitinitialized value in substitution
by kennethk (Abbot) on Mar 05, 2009 at 17:08 UTC
    The earlier thread includes the answer. In addition, you never initialize @rex, and thus never initialize either your match or replacement expressions.
Re: DBI, s/// => unitinitialized value in substitution
by swampyankee (Parson) on Mar 05, 2009 at 17:08 UTC

    Always use warnings and use strict; they will prevent many bad surprises. Using this you'd probably notice that @rex doesn't seem to have been set.


    Information about American English usage here and here. Floating point issues? Please read this before posting. — emc

      Thanks everyone. I did need as noted to initialize $_ to get s/// to work. I actually had initialized @rex, but inadvertently deleted it in my original post. Thanks again!
Re: DBI, s/// => unitinitialized value in substitution
by moritz (Cardinal) on Mar 05, 2009 at 17:07 UTC
    Where does @rex come from? Did you mean @row? Even if so, you're only selecting one value from the table, so $row[1] will always be uninitialized.

    And always remember to use strict;

Re: DBI, s/// => unitinitialized value in substitution
by locked_user sundialsvc4 (Abbot) on Mar 05, 2009 at 19:17 UTC

    I suggest that you re-code the statement to remove all doubt ... to eliminate any possible uncertainty about what those square-brackets might mean.

    my $foo = $rex[0]; my $bar = $rex[1]; s/$foo/$bar/ig;

    Realistically, it won't make any difference to the Perl compiler, and now “the designer's intentions are made clear.”