Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl how to take advantage of a block argument in my subroutine (like grep does)

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

like image 296
user2050516 Avatar asked Jan 03 '14 08:01

user2050516


1 Answers

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 );
like image 198
mpapec Avatar answered Oct 09 '22 16:10

mpapec