It's a really bad idea to modify globals (@ARGV and $_ in this case) without localizing them.
local @ARGV = ...;
local $_;
while (<>) {
...
}
| [reply] [d/l] [select] |
The delimit sub is designed to check and see if an infile is submitted and if it is remove any line from the $in_file that contains the characters espf[. The @ARGV while (<>) schema is because I got it from page 72 of my Learning Perl (4th addition) book.
| [reply] |
I think you are not well served by page 72 of Learning Perl.
It is far more clear, and much easier to debug, if you open the file directly, after checking, than in the background.
If you are feeling daring, then go with toolic's
open F, '<', $in_file or die "Can't open $in_file: $!";
followed by
while (<F>) {
push @lines, $_ unless /espf\[/
}
although if the goal is to edit $in_file deleting lines, then you probably don't want to push it into a temporary array, but instead open a temp file, write to the temp file, unlink $in_file, and rename the temp file to $in_file.
However, since this is probably doing a ton of disk access, I'd probably do a few sanity checks first.
return undef if not defined $in_file;
if (-e $in_file) {
if (-r $in_file) {
open F, "<", $in_file or die "Can't open $in_file: $!"
# etc
} else {
warn "can't read $in_file\n";
return undef;
}
} else {
warn "bad file $in_file submitted, but does not exist\n";
}
Part of the reason I say that reassigning ARGV is not good practice is the principle of least surprise. The "while (<>)" construct is best used in the fashion described in perlopentut:
One of the most common uses for open is one you never even notice. When you process the ARGV filehandle using <ARGV>, Perl actually does an implicit open on each file in @ARGV. Thus a program called like this:
$ myprogram file1 file2 file3
Can have all its files opened and processed one at a time using a construct no more complex than:
while (<>) {
# do something with $_
}
If @ARGV is empty when the loop first begins, Perl pretends you've opened up minus, that is, the standard input. In fact, $ARGV, the currently open file during <ARGV> processing, is even set to "-" in these circumstances.
While you *can* use the magic of an implicit open to open files, its better to avoid magic when possible for the next poor sap who has to debug your code.
--woody | [reply] [d/l] [select] |