in reply to Cleaner way of looping through a file and stripping only certain lines?
open IFILE, '<', "$ifile" || die "Couldn't open file: $!";
is buggy. Due to the operator order or precedence, it's equivalent to
open IFILE, '<', ("$ifile" || die "Couldn't open file: $!");
You want one of the following instead
open IFILE, '<', "$ifile" or die "Couldn't open file: $!";
open(IFILE, '<', "$ifile") || die "Couldn't open file: $!";
open(IFILE, '<', "$ifile") or die "Couldn't open file: $!";
(open IFILE, '<', "$ifile") || die "Couldn't open file: $!";
(open IFILE, '<', "$ifile") or die "Couldn't open file: $!";
Same goes for the second open.
Why "$ifile" instead of just $ifile?
Why '+>' instead of just '>'?
/^@.*mail(\d+).*\z/xms
can be simplified to
/^@.*mail(\d+)/xms
All three modifiers (xms) could be removed from the match operator, but they cause no harm here.
The user doesn't need to see the program line number when he specifies a bad file name. If the error message is not good enough to identify a user error without resorting to a line number, it needs to be improved.
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 | |
by revdiablo (Prior) on Dec 08, 2006 at 18:17 UTC | |
by texasperl (Sexton) on Dec 08, 2006 at 18:20 UTC | |
by ikegami (Patriarch) on Dec 08, 2006 at 19:10 UTC | |
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 |