Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl: the Markov chain saw
 
PerlMonks  

Re: Predefining sub Parameters

by techcode (Hermit)
on Jun 22, 2005 at 23:41 UTC ( #469244=note: print w/ replies, xml ) Need Help??


in reply to Predefining sub Parameters

While most of people gave you various (and very good) responses. I'd like to comment on this.

I really like this way it's done in Perl. Sure it takes a bit of time to adjust to it - but once you do that. It comes somehow naturally.

Also - once I discovered how hashes are great (before Perl I only used C on university, and some Basic variants like M$ VB and old Amiga AMOS on my own) I started almost just using them :)

They are so great because many of the modules use them, and at the end of the day, my jobs ends up in passing references from one module to other :)

In your case (actually in almost any case) I would probably use something like:

sub_call ({ first => $first, second => \@second, third => $third, }); # ... sub sub_call { my $hash_ref = shift; # $hash_ref->{first} holds original $first # $hash_ref->{second} holds reference to original @second # $hash_ref->{third} holds original $third # NOTICE - just like passing pointers in C. # When you modify the array that array_ref points to (to @second) # you are changing the original. Might not be what you want. # In that case, pass @second, not \@second to get a "local copy" }
Or other similar option: < EDIT: As sugested a little earlier >
sub_call ( first => $first, second => \@second, third => $third, ); sub sub_call { my %hash = @_; # $hash{first}, $hash{second}, $hash{third} hold values like above }

Good thing about this, is that when you write the sub, you don't need to set the local variable for each sent parameter. The order of parameters also isn't important, but caller needs to know exact names that you use through the sub. IMHO I just like this way better.

While you can use any of the above, first one (passing reference) should be better in case you have many variables (in this case tree, since we pass array_ref). I would suggest you actually use just it.
So you wouldn't come into a doubt which one did you used for particular sub. And be constant in it.
Maybe someone wouldnt agree with all this?

I also noticed that many CPAN modules use this for configuration type method calls.

PS. This way you predefine the names of the variables but not their placing in sub call :)


Comment on Re: Predefining sub 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://469244]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others examining the Monastery: (7)
As of 2014-09-16 06:24 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite cookbook is:










    Results (157 votes), past polls