grep can be invoked in two ways as listed below. I properly miss a piece of information to understand this block magic. Maybe a good soul can explain to me how grep internal gets a reference to the block and deals with that or even better how can I write a subroutine which uses the bock notation.
1) This is what I consider the traditional way.
grep EXPR,LIST
example: @foo = grep(!/^#/, @bar);
2) This is nice and neat but magic to me.
grep BLOCK LIST
example: @foo = grep {!/^#/} @bar;
Many thanks in advance.
BR/Hermann
Check prototypes
sub mygrep (&@) {
my $f = shift;
return map { $f->() ? $_ : () } @_;
}
print join "\n", mygrep { $_%2 } 1..10;
Same thing as above, but without prototypes,
sub mygrep {
my $f = shift;
return map { $f->() ? $_ : () } @_;
}
print join "\n", mygrep( sub{ $_%2 }, 1..10 );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With