in reply to Regular Expressions to ignore lines starting with #

Instead of using:

open FILE,"tnsnames.ora" or die $!; {local $/=undef; $_ = <FILE>; } close FILE;

I'd probably use something like this:
open(FILE, '<', 'tnsnames.ora') or die "Cannot open tnsnames.ora for reading, stopped ",$!; my $tnsnames = ''; for (<FILE>) { next if /^#/; $tnsnames .= $_; } close FILE;

It will skip the lines beginning with # and add all the rest into the scalar $tnsnames.

Replies are listed 'Best First'.
Re: Re: Regular Expressions to ignore lines starting with #
by sauoq (Abbot) on May 19, 2003 at 18:43 UTC
    next if /^#/;

    I'd likely do it similarly but I'd change the regex a bit. Using /^\s*#/ will skip lines where the first non-whitespace character is an octothorpe, not just the first character. That's usually how comments are defined.

    -sauoq
    "My two cents aren't worth a dime.";
    

      and i would do it like this:

      s/#.*$//; next if /^$/;

      to remove any comment (up to end of line) and skip if there's nothing left. but this might be stretching the requirement a bit.

        s/#.*$//; next if /^$/;

        That'll probably bite you eventually. Consider these lines from an imaginary configuration file:

        # Set the format for currency: currency_format = '$###.##';

        Skipping comment-only lines right off the bat is an optimization. Other lines will probably require smarter parsing.

        Even if the file format guaranteed that your method could be used safely, I wouldn't use it. Why do an expensive substitution on lines you are going to throw out? I'd do it like this:

        next if /^\s*#/; s/#.*$//;

        We've probably strayed quite a bit from the OP's needs though.

        -sauoq
        "My two cents aren't worth a dime.";
        
      I use to do it like:
      next if /^\s*(#.*)?$/;
      skipping "empty" lines too, which of course will fail if you use HERE document like constructs.
        I have tried all the combinations that you all have suggested and I understand the syntax but the pattern I am looking for is not being identified in the first file only in the 2nd file and I can't understand why, because they have basically both the same info with some exceptions.