in reply to Search and replace within a file

See quotemeta and Iterator::Diamond

#!/usr/bin/perl -- use strict; use warnings; use Iterator::Files; my $search = quotemeta `uname -r`; my $input = Iterator::Files->new( files => [ '/etc/hosts' ], ); while( <$input> ){ s/$uname/$answer1/g; s/\Qdomainsuffix.net\E/$answer4/g; }

Replies are listed 'Best First'.
Re^2: Search and replace within a file
by muizelaar (Sexton) on May 08, 2012 at 11:11 UTC

    Just been reading up on this and it looks very useful, but I’m not sure if this is what I want. Sorry if I haven’t been very clear.

    Where I have s/$uname/$answer/g; it’s the $uname part which is not changing within the hosts file

    However it does change it after the FQN name part within the hosts file

      So you're trying to say that $uname doesn't match as a regular expression?

      Doesn't using quotemeta change that?

      Maybe you want to add case insensitivity (s///i) ?

      See How do I post a question effectively? and write this

      #!/usr/bin/perl -- use strict; use warnings; use Data::Dump qw/ dd /; my $input = 'servername.EXAMPLE.com servername'; my $wantedOutput = 'newname.EXAMPLE.com newname'; my $replacement = 'newname'; my $uname = quotemeta 'servername'; ### dd $input; for( $input ){ s/$uname/$replacement/gi; } dd $input; dd $wantedOutput ; __END__ "servername.EXAMPLE.com servername" "newname.EXAMPLE.com newname" "newname.EXAMPLE.com newname"

      As you can see through my use of Data::Dump::dd, it worked, $input has changed and it now looks like $wantedOutput

        Hi

        Yes that’s correct $uname is not being replaced. If I remove the $uname and place for example XXXXXXX within the code and also place this into the /etc/hosts file it does replace it. Its only when I use the scalar $uname it doesn’t seem to work.

        s/XXXXXXX/$answer1/g;

        As suggested I’ll give quotemeta a go and see if that works. Thanks for your help with this anyway