- You are attempting to read (while(<FILE>){) from your output file. You'll never reach the print.
- push @new, $i; adds undef for the lines grep matched.
- ($i)= grep { m/^#/ } $_; keeps the comment lines instead of the lines without comments.
- for(@array){ ($i)= grep { m/^#/ } $_; push @new, $i; }
should be
@new = grep { !m/^#/ } @array;
- You don't check if your open succeeded
open(FILE, "<$file") or die("Unable to open input file \"$file\": $!\n");
open(FILE, ">$nfile") or die("Unable to create output file \"$nfile\": $!\n");
- You should use the 3-arg open whenever possible.
open(FILE, '<', $file)
open(FILE, '>', $nfile)
- You should use lexicals whenever possible.
open(my $fh_in, '<', $file) (while (<$fh_in>))
open(my $fh_out, '>', $nfile) (print $fh_out ...)
- Shouldn't $file=<>; be $file=@ARGV[0];?
Shouldn't $nfile=<>; be $nfile=@ARGV[1];?
Parameters are usually passed as parameters instead of via STDIN. If you do mean to read from STDIN, give the user a prompt, and use <STDIN> instead of <>.
- No checking to see if $file and $nfile were specified. (They could be undef.)
- The trailing newline is not removed from $file and $nfile.
- Why read the whole file into memory?
Fix: (one-liner) ( Added missing >. Thanks Hofmator. )
perl -ne "print unless /^#/" infile > outfile
Fix: (program -- memory efficient)
use strict;
use warnings;
die("usage: $0 {infile} {outfile}\n";
if @ARGV != 2;
my ($file_in, $file_out) = @ARGV;
open(my $fh_in, '<', $file_in)
or die("Unable to open input file \"$file_in\": $!\n");
open(my $fh_out, '>', $file_out)
or die("Unable to create output file \"$file_out\": $!\n");
while (<$fh_in>) {
if (!/^#/) {
print $fh_out $_;
}
}
Fix: (program -- (more) compact)
use strict;
use warnings;
die("usage: $0 {filein} {fileout}\n";
if @ARGV != 2;
my ($file_in, $file_out) = @ARGV;
open(my $fh_in, '<', $file_in)
or die("Unable to open input file \"$file_in\": $!\n");
open(my $fh_out, '>', $file_out)
or die("Unable to create output file \"$file_out\": $!\n");
print $fh_out (grep !/^#/, <$fh_in>);