in reply to Re: Simple regexp question
in thread Simple regexp question
-
"$filename"
doesn't need to be in quotes.
$filename
will do fine. -
open INFILE, '<', $filename
is less error-prone and safer than the two-arg version. -
It's good to use local variables for file handles. Replace
open INFILE, '<', $filename
with
open local *INFILE, '<', $filename
or
open my $fh_in, '<', $filename -
open local *INFILE, '<', $filename || die "cant open the input file";
is the same as
open local *INFILE, '<', ($filename || die "cant open the input file");
which is definitely not what you want. Use
open(local *INFILE, '<', $filename) || die("Unable to open the input file: $!\n");
or
open local *INFILE, '<', $filename or die "Unable to open the input file: $!\n"; -
We don't need to know how many # and * we have in a row, so
if (/[\#\*]+/)
can be simplified to
if (/[\#\*]/)
And since # and * are not special in character class, you don't need to escape them. The following in sufficient.
if (/[#*]/)
Also, the parens are optional on a if suffix, and just add clutter in this case. I'd remove them as follows:
if /[#*]/ -
I think "to filter out lines" means "to remove lines". If so, replace
if /[#*]/
with
unless /[#*]/ -
Your print is adding spaces. Replace
print "@filtered";
with
print @filtered;
We get the following:
open(local *INFILE, '<', $filename) or die("Unable to open the input file: $!\n"); my @filtered; while (<INFILE>) { push(@filtered, $_) unless /[#*]/; } print @filtered;
What follows is a more elegant but more memory intensive alternative:
open(local *INFILE, '<', $filename) or die("Unable to open the input file: $!\n"); my @filtered = grep { !/[#*]/ } <INFILE>; print @filtered;