As a default value.
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:
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($_);
}
}
You can see that the construct with the default value is much shorter (3 instead of ~8 lines), and it's much cleaner.
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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|