Yes, Perl has grep and map but is missing this idiom, which is why I added it to Algorithm::Loops as Filter(). But I still use grep to remove selected lines, which makes the map w/ "local $_= $_;" version appealing.
use Algorithm::Loops qw( Filter ); my @lines = grep defined, Filter { s/^\s+//; if( /^#/ ) { undef $_; } else { s/\s+$//; } } <$in>;
It isn't terribly hard to do "filtering" directly with grep or map, but it is terribly easy to only get filtering almost right with them and the difference is usually subtle but can still lead to real problems.
A pragma to make the aliases that map and grep provide in $_ always be read-only would be something I would use... I wonder if Perl6 lets you specify "read-only aliases" vs. "read-write copies" vs. "read-write aliases" for map / grep like I know it will for function arguments.
A concise alternative:
s/^\s+//, s/\s+$// for my @lines= grep ! /^\s*#/, <$in>;
- tye
In reply to Re: A perverse use of grep (filtering)
by tye
in thread A perverse use of grep
by eyepopslikeamosquito
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |