in reply to Re^2: what is sub {1;}
in thread what is sub {1;}
Suppose you write a sub (or module) that processes some values, and you want to offer the caller the possibility to filter some of them. Now you've got two options:
You can see that the construct with the default value is much shorter (3 instead of ~8 lines), and it's much cleaner.sub process { my ($data, $filter) = @_; # lengthy calculations with $data here ... # in that length calculation you have to decide # if you continue with your calculation: for (@$data){ if ($filter) { if ($filter->($_)){ push @$data, other_lengthy_calculation($_); } } else { push @$data, other_lengthy_calculation($_); } } # second option: sub process { my ($data, $filter) = @_; # provide a default value for $filter $filter = sub {1;} unless $filter; # lengthy calculations with $data here ... # in that length calculation you have to decide # if you continue with your calculation: for (@$data){ if ($filter->($_)) { push @$data, other_lengthy_calculation($_); } }
If you're interested in more details on callbacks, anonymous subs and many more advanced techniques, I strongly recommend the book "Higher Order Perl" by Mark Jason Dominus.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^4: what is sub {1;}
by ruzam (Curate) on May 27, 2008 at 14:06 UTC | |
by moritz (Cardinal) on May 27, 2008 at 14:14 UTC |