I’m a big fan of functional programming, so when I discovered block references in Perl I started using them a lot.
However, the functions I’ve written that take blocks as arguments are written in this style:
sub mygrep (&@) {
my $code = shift;
my @result;
foreach $_ (@_) {
push(@result, $_) if &$code;
}
@result;
}
(From http://perldoc.perl.org/perlsub.html#Prototypes)
In essence, most of my functions set $_ in order for the code block to gain access to data in my sub. I guess my question can be split into three subquestions:
- Are there some major pitfalls in this approach?
- Is it a better idea to
localize$_before setting it? - Should i use partially applied functions instead?
I’m still a Perl newbie so any answers and suggestions are appreciated – thanks in advance! 🙂
my $_;in view of the block will hide your changes to package variable$_. There’s nothing you can do about that from inside ofmygrep.&$codeis very special. You want&$code()or$code->()instead.Changing
$_will change the arguments passed tomygrep. That’s undesirable here.forprovides much better localisation thatlocal, but it also provides aliasing that’s undesirable here.I don’t know what that means.
Fixed:
That said, I think
mygrepis kind pointless, sincemap+grepalready does what you want more easily. Comparewith
You can even merge the
mapandgrep.