in reply to Regex triggering uninitialised values

Make the \d optional, not the capture:

use strict; use warnings; my $str; #$str = "6%var% after"; $str = "%var% after"; # <-- warning is triggered $str =~ s/(\d?)%var%(.*)/$1REPLACED$2/; # <-- moved the '?' print "$str\n"

By the way, I don't get the warning under Active Perl 5.6.1, but I did with perl v5.8.0 built for i386-freebsd

Replies are listed 'Best First'.
Re^2: Regex triggering uninitialised values
by kiat (Vicar) on Nov 19, 2004 at 17:49 UTC
    Thanks, ikegami!

    How will the regex change if I need to match more than one digit before %var%? Just can't think of anything at the moment...

    Edited: Sorry, just discovered that moving the ? solves the problem.

    #$str =~ s/(\d+?)%var%(.*)/$1REPLACED$2/;</strikeout> As pointed out by Eimi Metamorphoumai $str =~ s/(\d*)%var%(.*)/$1REPLACED$2/;</strikeout>
      Watch out! '+?' isn't the same as '*' in a regexp. If you want zero or more, you want '*'. '+?' will only match if there is one or more, but will match non-greedily (that is, as few characters as possible).
        Ah, thanks!