Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

regex substitute(resolved)

by anaconda_wly (Scribe)
on May 16, 2013 at 03:53 UTC ( #1033760=perlquestion: print w/ replies, xml ) Need Help??
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.

Comment on regex substitute(resolved)
Select or Download Code
Re: regex substitute(resolved)
by Athanasius (Monsignor) 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 (Prior) 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*//;

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://1033760]
Approved by kcott
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others scrutinizing the Monastery: (7)
As of 2014-10-25 16:33 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (145 votes), past polls