in reply to Unix 'grep -v' equivalency in Perl (was: Perl Regex Question)

First of all, you are not opening the file right. Try:
open(IN,$log) || die $!, "\n";
Always have an '|| die' when you are opening a file. If the file fails to open and you continue anyway, you'll eventually get an error for trying to work on a closed filehandle, and your script will die anyway.

Second of all, you seem to using '$_' correctly so I wouldn't worry about that.

However in order to get a non-match you would need to use the expression:

if ( $_ !~ m/$i/ ) { print; }
The key there being the '!~' operator.

Update: I've been advised to not use the '|| die' notation and use instead 'or die'. As far as I can see this has to do with the trouble that could be caused by combining this notation with a function call that does not use parentheses.

The higher precedence of '||' causes Perl to see the call differently than if the 'or die' notation was used(when making a function call sans parentheses). Example:

open FH, "filename" or die $!; #will read as its meant to: open(FH,"filename") or die $!; open FH, "filename" || die $!; #will read as: open FH,("filename" || die $!); which is not good since + the only time #this expression will be treated as false is in cases where filename i +s an undefined expression(0,"",or undefined scalar) #but unrecognized file names will not be evaluated as false so the die + will serve no purpose and the the script will continue to run

Amel - f.k.a. - kel

Replies are listed 'Best First'.
Re: Re: Unix 'grep -v' equivalency in Perl (was: Perl Regex Question)
by Zaxo (Archbishop) on Jul 10, 2001 at 06:07 UTC

    Just a brief addition to this. You'll get more information by leaving off the "\n".

    open(IN,$log) || die $!, "\n"; #or #open(IN,$log) || die "$!\n";

    Gives the message:

    No such file or directory

    While

    open(IN,$log) || die $!;

    gives

    No such file or directory at ./die line 5.

    This behavior is documented in perldoc perlfunc die

    After Compline,
    Zaxo

Re:{2} Unix 'grep -v' equivalency in Perl (was: Perl Regex Question)
by jeroenes (Priest) on Jul 10, 2001 at 15:28 UTC
    Yet another brief addition: the message $! tells you the cause of the addition, but not the source. Zaxo already told you that leaving that newline out makes die tell the terminal which line of code generated that error.

    However, that's not immediately informative. The command probably interpretets a variable to generate the syscall, so in general it's a good idea to provide that information :

    open( INPUT, $filename ) or die "Could not open $filename: $!"; # or rename( $old, $new ) or die "Could not rename $old to $new: $!";

    As a third step, you can use Carp to print out the chain of callers. This is useful when your code is distributed over more than one file.