Beefy Boxes and Bandwidth Generously Provided by pair Networks
Don't ask to ask, just ask
 
PerlMonks  

Re^4: Refactoring Perl #7 - Remove Assignments to Parameters

by agianni (Hermit)
on Aug 23, 2007 at 15:57 UTC ( #634676=note: print w/ replies, xml ) Need Help??


in reply to Re^3: Refactoring Perl #7 - Remove Assignments to Parameters
in thread Refactoring Perl #7 - Remove Assignments to Parameters

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...


Comment on Re^4: Refactoring Perl #7 - Remove Assignments to Parameters
Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://634676]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others surveying the Monastery: (7)
As of 2014-07-11 00:51 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    When choosing user names for websites, I prefer to use:








    Results (217 votes), past polls