in reply to File read and strip
Don't mind me, I'm just in a bit of a weird mood, so pardon me while I have a little twisted fun at the expense of your code...
use strict; use warnings; my $file=<>; open FILE, '<', $file; my @new = map { grep { m/^#/ } } <FILE>; close FILE; my $nfile=<>; open FILE, '>', $nfile; print FILE map{" \n\n $_ \n\n "}@new for <FILE>;
Ah. Hopefully that's out of my system now.
So, then, on to fixing it... First off, the print statement is never happening because <FILE> does not return anything very useful when the file is opened for output. Second, the test in grep is probably backwards from what you want.
use strict; use warnings; my $file=<>; open FILE, '<', $file; my @new = map { grep { not m/^#/ } } <FILE>; close FILE; my $nfile=<>; open FILE, '>', $nfile; print FILE map{" \n\n $_ \n\n "}@new for 1, <FILE>;
This is still not optimal. For one thing, the first map (corresponding to your first while loop in the original code) is obviously superfluous. (Your while loop in the original wasn't necessary either, but it's more obvious to me now.) Second, there's still the weird double-indirection surrounding the filenames, which others have commented about. Third, I prepended a true value to force the print statement to occur once, but the file read there is still nonsense. Finally, there are still more variables than are strictly necessary; some of them are only used once -- well, twice: once in an assignment, and once again on the very next line to use the value; this amounts basically to using them once to turn one line into two, and that isn't necessary...
use strict; use warnings; open FILE, '<', scalar <>; my @new = grep { not m/^#/ } <FILE>; close FILE; open FILE, '>', scalar <>; print FILE map{" \n\n $_ \n\n "}@new;
If you're willing to add a second filehandle you can get rid of the array, and the whole thing could be reduced to more-or-less a one-liner...
use strict; use warnings; open INFILE, '<', scalar <>; open OUTFILE, '>', scalar <>; print OUTFILE map{" \n\n $_ \n\n "} grep { not m/^#/ } <INFILE>;
Look, ma, no variables to declare. If you're willing to use standard input and output and let the user specify the filenames with redirection operators, it becomes a veritable one-liner:
print map{" \n\n $_ \n\n "}grep{not m/^#/}<STDIN>;strict and warnings seem unnecessary on anything that short. Someone will probably come along in a moment and explain how to use command-line flags to shorten it even further.
|
|---|