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

Monks, I've been struggling with a particular segment of my 300-line program I've been writing. I've added a remove function from <> to pass the string to the interpreter, I tell Perl to have a look at a file to find this string. If it exists the ENTIRE line that held that string will be deleted.

Should I use:
if ($remove eq ~ m/^.*\b($remove)\b.*$) { # do stuff here }
OR:
sub clean_the_file { my $sourcefile = "/u/ccsys/CC_print.printers"; # grab the sourcefile and the string to remove as the first and second + arguments my ( $sourcefile, $remove ) = @_; # create a temporary file my $tempfile = # Some random file creation logic; # extract lines from $sourcefile which do NOT have the string to r +emove # note that the \' inserts ticks so that strings with spaces can w +ork, too `grep -v \'$remove\' $sourcefile\n > $tempfile`; # delete source file, then rename working file unlink($sourcefile); rename( $tempfile, $sourcefile ); }
Obviously the second logic makes a bit more sense; considering I'm not editing a live file, IF: the second logic should be used, how would I go about generating a random filename?

Replies are listed 'Best First'.
Re: Pattern matching || grep -v which logic is better?
by FunkyMonk (Bishop) on Feb 08, 2008 at 15:24 UTC
    Should I use:

    if ($remove eq ~ m/^.*\b($remove)\b.*$) { # do stuff here }
    It doesn't compile, so I wouldn't use it:-)

    Perhaps you meant something like:

    if ( m/\b$remove\b/ ) { # do stuff here }

    how would I go about generating a random filename?
    See File::Temp

Re: Pattern matching || grep -v which logic is better?
by olus (Curate) on Feb 08, 2008 at 15:21 UTC
    use strict; use warnings; my @lines = <DATA>; my @greped = grep {! /remove/} @lines; print foreach @greped; __DATA__ 1 String not in this line 2 remove is here 3 but not here
Re: Pattern matching || grep -v which logic is better?
by CountZero (Bishop) on Feb 08, 2008 at 16:21 UTC
    For making a temporary file in a safe and portable way, have a look at File::Temp. It can even make temporary files which delete themselves at the end of the script or when they go "out-of-scope", but you probably want to avoid that kind of magic in your script..

    CountZero

    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James