http://www.perlmonks.org?node_id=1033760

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

I got a string $ou "# PATH=$PATH:$NAS_DB/sbin:$NAS_DB/bin:$NAS_DB/sbin" and want to delete the heading # and the white space around.

my $ou ="# PATH=\$PATH:\$NAS_DB/sbin:\$NAS_DB/bin:\$NAS_DB/sbin"; print __FILE__." line".__LINE__." trace: ".$ou."\n"; if($ou =~ /^\s*#\s*(PATH=.*\$NAS_DB\/bin.*)$/) { my $str = $1; $ou=~s/^\s*#\s*PATH=.*\$NAS_DB\/bin.*$/$str/; print __FILE__." line".__LINE__." trace: ".$ou."\n"; }

When I remove $str, replace it with $1, the output is empty. Not what I want. So why? Every thanks.

my $ou ="# PATH=\$PATH:\$NAS_DB/sbin:\$NAS_DB/bin:\$NAS_DB/sbin"; print __FILE__." line".__LINE__." trace: ".$ou."\n"; if($ou =~ /^\s*#\s*(PATH=.*\$NAS_DB\/bin.*)$/) { $ou=~s/^\s*#\s*PATH=.*\$NAS_DB\/bin.*$/$1/; print __FILE__." line".__LINE__." trace: ".$ou."\n"; }
OK, I got it. Seems $1 was reset after every matching.

Replies are listed 'Best First'.
Re: regex substitute(resolved)
by Athanasius (Archbishop) on May 16, 2013 at 04:13 UTC
    Seems $1 was reset after every matching.

    Correct. The pragma use warnings would tell you:

    Use of uninitialized value $1 in substitution iterator at...

    which indicates that $1 is undef, because nothing has been captured in the current substitution. Easily fixed by adding parentheses to capture the text you want to keep:

    $ou =~ s/^\s*#\s*(PATH=.*\$NAS_DB\/bin.*)$/$1/;

    Hope that helps,

    Athanasius <°(((><contra mundum Iustus alius egestas vitae, eros Piratica,

      Yes, fine. Thank you!
Re: regex substitute(resolved)
by hdb (Monsignor) on May 16, 2013 at 06:29 UTC

    Unless you really need to confirm the structure of the path itself, the easiest way to remove the leading # and the surrounding whitespace would be:

    $ou =~ /^\s*#\s*//;