Excellent! I guess this refactoring pattern maps nicely to TheDamian's Always unpack @_ first best practice (PBP, p. 178).
Update: Actually, after thinking about it a bit, it doesn't map exactly. Consider:
my $array_ref = [ qw( 1 4 9 10 15 23 34 84 100 ) ];
add_n_to_values_and_print( $array_ref, 15 );
sub add_n_to_values_and_print{
my ( $list, $add ) = @_;
for my $value ( @$list ){
$value += $add;
print $value;
}
}
This follows Mr. Conway's admonition to unpack @_ but it doesn't accomplish the goal of avoding changes to the reference passed in that Fowler is after. What we really need to do is:
my $array_ref = [ qw( 1 4 9 10 15 23 34 84 100 ) ];
add_n_to_values_and_print( $array_ref, 15 );
sub add_n_to_values_and_print{
my ( $list, $add ) = @_;
# dereference and work with a local copy of the array
my @local_list = @$list;
for my $value ( @local_list ){
$value += $add;
print $value;
}
}
Truthfully, that's not a very good example, as I wouldn't generally write code that actually updates the value I would probably write print $value + $add, but for the sake of an example...
-
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.