Question

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

Était-ce utile?

La solution

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 );
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top