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

I'm curious to see what my fellow monks think of this piece of code for searching and replacing a line in a file. It works like I want it too but I'm wondering how many different ways there are to do this and how bad my code is.. Any advise would be greatly appreciated.
#!/usr/bin/perl -w # # simple search and replace script - # for a snort rule # use strict; my $policy_file = "/usr/local/snort/rules/rules-new/policy.rules"; open(FILE,"$policy_file"); my @old_policy = <FILE>; close(FILE); open(FILE,">$policy_file"); for (@old_policy) { if (/^alert ip 63.251/) { $_ = "#$_"; } print FILE $_; } close(FILE);
Thanks,

--JD

Replies are listed 'Best First'.
Re: Simple Search and Replace?
by dragonchild (Archbishop) on Mar 26, 2003 at 18:04 UTC
    perl -pie 's/^alert ip 63.251/#$_/' will do it just fine. :-)

    ------
    We are the carpenters and bricklayers of the Information Age.

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

Re: Simple Search and Replace?
by zby (Vicar) on Mar 26, 2003 at 18:10 UTC
    There is that -i switch for replacing files. Together with other switches your program could be a lot shorter:
    perl -pi.bak -e 's/(^alert ip 63.251)/#$1/;'
    This code makes a backup too.
      Thanks to all!

      I really like the '-i' switch. Where in perldoc could you find this type of information?


      --JD
        Nevermind... I found the answer. "perldoc perlrun"!

        --JD
        perldoc perlrun.
Re: Simple Search and Replace?
by OM_Zen (Scribe) on Mar 26, 2003 at 18:10 UTC
    Hi ,

    The assignment of file contents to an array surely depends on the size of the file .The file , if it has a larger size will consume whole of the memory either dumping core or exiting out with some untrappable error. Hence people tend to use while to read and print in the write file
    while (<readthefile>) $_ =~ s///g; print WriteData "$_"; print "$/"; }


    The read os data if it is small in size you could set  $/ = undef; and slurp the file contents to a ascalar variable itself and then do the regular expression on it .

Re: Simple Search and Replace?
by nadadogg (Acolyte) on Mar 26, 2003 at 20:39 UTC
    i did it like this. My script was replacing characters, but it can do more.
    sub fixspace{ $rem ="bob"; $rep = "john"; open FILE, "<$file"; open OUTP, ">c:\\joshperl\\deptemp.txt"; while (<FILE>) { s/$rem/$rep/go; print OUTP; } close FILE; close OUTP; }