Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re: Newbie question

by stevieb (Canon)
on Aug 23, 2022 at 21:03 UTC ( [id://11146338]=note: print w/replies, xml ) Need Help??


in reply to Newbie question

It is, in my humble opinion, best practice to collect up the incoming parameters of a subroutine as soon as humanly possible so while reading into the function/method, it's easy to see what is what (the length of the variable name isn't my normal style, I've just made it readable for the example):

sub oddDigitSum { my @signed_integers_to_work_on = @_; my @ans; for (@signed_integers_to_work_on) { ...

To further, I always check my input parameters, even if a built-in will throw an exception on them anyway (the regex isn't always my normal way of checking, but it's good as an illustrative example):

sub oddDigitSum { my @supplied_signed_integers = @_; my @ans; for my $signed_int (@supplied_signed_integers) { if ($signed_int !~ /^-?\d+$/) { die "Parameter '$signed_int' isn't a signed integer"; ...

For me, I use the implicit $_ variable when my loop is exceedingly short in lines of code, or the complexity of the loop is only one level deep and very clear to understand. Your for() loop is a good example of where I'd use $_ and not bother declaring and defining a named scoped variable for each value being iterated as I did in an above example. If there was even one more operation in that for() loop though, I'd break it up with named variables, just so its easier to a future reader (often me) which operation modified the list.

Replies are listed 'Best First'.
Re^2: Newbie question
by oldB51 (Sexton) on Aug 24, 2022 at 07:03 UTC

    Thanks for this stevieb. I have amended my code so as to check input parameters. For the moment I have done it by returning a nice friendly message rather than using  die. However, I will be returning to this when I can study errors properly.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others meditating upon the Monastery: (6)
As of 2024-04-19 10:23 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found