I noticed this code today:
It caught my eye because it seems stylistically dubious in that grep should be used to select from a list, while here it's being used to modify the list. It also contains a subtle bug in that lines consisting of a bald zero (0) will be erroneously discarded. Now, I could fix this bug with:# Read a text file, stripping leading and trailing whitespace # and ignoring any lines starting with '#' my $file = shift; open(my $in, '<', $file) or die "error: open $file: $!"; my @lines = grep { s/^\s+//; s/#.*//; s/\s+$//; $_ } <$in>; close($in); for my $x (@lines) { print "x='$x'\n" }
or:my @lines = grep { s/^\s+//; s/#.*//; s/\s+$//; length($_) } <$in>;
though I'm not especially happy with either of these. How would you do it?my @lines = map { s/^\s+//; s/#.*//; s/\s+$//; length($_) ? $_ : () } +<$in>;
In reply to A perverse use of grep by eyepopslikeamosquito
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |