in reply to Cleaner way of looping through a file and stripping only certain lines?

With changes applied:

#!/usr/bin/perl -w use strict; my $ifile = shift; my $ofile = 'new_data'; open my $ifh, '<', $ifile or die "Couldn't open DNS file \"$ifile\": $!\n"; open my $ofh, '>', $ofile or die "Couldn't create output file \"$ofile\": $!\n"; while (my $line = <$ifh>) { # is the line an MX record? if ($line =~ /^@.*mail(\d+)/xms) { # is it less than or equal to 8? if ($1 <= 8) { print $ofh $line; } } # print everything else to the new file else { print $ofh $line; } }

You could make your program sipler and more flexible by using STDIN and STDOUT.

#!/usr/bin/perl -w use strict; # # Usage: # fixdns infile > outfile # # Usage for in place editing: # perl -i fixdns dnsfile # while (<>) { # is the line an MX record? if (/^@.*mail(\d+)/xms) { # is it less than or equal to 8? if ($1 <= 8) { print; } } # print everything else to the new file else { print; } }

Replies are listed 'Best First'.
Re^2: Cleaner way of looping through a file and stripping only certain lines?
by texasperl (Sexton) on Dec 08, 2006 at 18:05 UTC
    This is some great insight. I especially gleaned a lot of wisdom from these bits:
    • not using "" around the variable in open
    • operator precedence in the open statement
    • using STDIN and STDOUT instead of named filehandles
    Thank you very much for your excellent insight. Hopefully someone else can also learn from this post (that's why I post things like this.)
      operator precedence in the open statement

      Not trying to kick you while you're down (honestly! =]), and it could just be a case of me misreading your sentence, but the operator precedence ikegami explained is not limited to the open statement -- it's part of the perl parser in general.

      Update: Ah, misread the original sentence indeed. Sorry 'bout that. No harm intended.

        Ha! It was a case of misreading the sentence. All the same, thanks for the reminder. Now...the task of fixing my short-circuiting/error messages in other scripts awaits me. =]
Re^2: Cleaner way of looping through a file and stripping only certain lines?
by duckyd (Hermit) on Dec 08, 2006 at 20:01 UTC
    I would add that you can avoid the use of a bareword filehandle by calling open with an undef scalar instead:
    open my $input_fh, '<', "$ifile" or die "Couldn't open file: $!";
    now use $input_fh just like you would have used IFILE