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

Hi all, I'm new here and must confess my perl knowledge is very limited. I'm trying to use a perl script that will replace a line in an other html file on the same box. Problem is that there are brackets ( ) in the text that I want to replace and I can't find a way to get it to work. Here is my code:

my $filename = '/tmp/somefile.html'; my $find = "<option SELECTED>[ Current time range ]"; my $replace = '<option SELECTED> Current time'; { local @ARGV = ($filename); local $^I = '.bac'; while( <> ){ if( s/$find/$replace/ig ) { print; } else { print; } } }

  • Comment on How to replace a piece of text containing brackets in an external file
  • Download Code

Replies are listed 'Best First'.
Re: How to replace a piece of text containing brackets in an external file
by LanX (Saint) on Dec 15, 2012 at 21:19 UTC
    You need to escape the brackets otherwise they have a special meaning (character classes) in regex syntax.

    Either you write $find='...\[...\]' or you use \Q for quoting s/\Q$find/.../.

    DB<114> $_='abc[de]' => "abc[de]" DB<115> $find='c[de]' => "c[de]" DB<116> $find2='c\[de\]' => "c\\[de\\]" DB<117> m/$find/ # no match DB<118> m/$find2/ # match => 1 DB<119> m/\Q$find/ # match => 1 DB<120> "\Q$find" # how \Q=quotemeta works => "c\\[de\\]"

    Cheers Rolf

      Thank you very much, quotemeta solved my problem!
Re: How to replace a piece of text containing brackets in an external file
by tobyink (Canon) on Dec 15, 2012 at 21:28 UTC
    my $filename = '/tmp/somefile.html'; my $find = quotemeta "<option SELECTED>[ Current time range ]"; my $replace = '<option SELECTED> Current time'; { local @ARGV = ($filename); local $^I = '.bac'; while( <> ){ if( s/$find/$replace/ig ) { print; } else { print; } } }

    Or, with a saner while loop...

    my $filename = '/tmp/somefile.html'; my $find = quotemeta "<option SELECTED>[ Current time range ]"; my $replace = '<option SELECTED> Current time'; { local @ARGV = ($filename); local $^I = '.bac'; while( <> ){ s/$find/$replace/ig; print; } }
    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: How to replace a piece of text containing brackets in an external file
by Anonymous Monk on Dec 16, 2012 at 01:00 UTC