Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

Re: Newbie question

by hv (Prior)
on Aug 23, 2022 at 16:19 UTC ( [id://11146327]=note: print w/replies, xml ) Need Help??


in reply to Newbie question

As an example, I have used the absolute value function abs but I could have used abs($_). Which is best? Does it matter?

Specifically on this point: others have pointed out that there is no difference functionally, so that leaves style and clarity to drive the choice.

In my case, I hardly ever use the abs function (despite the fact that most of the code I write is maths-related). Because of that, I would choose always to write $abs = abs($_); rather than $abs = abs; - for the latter, I'd have to stop and think a few deciseconds longer any time I wrote it or read it.

On the other hand, for functions that default to $_ that I use commonly, I'm much more likely to prefer the short form.

On the gripping hand, I try to avoid over-reliance on $_. Normal for loops are almost always improved by naming the variable. I mostly have $_ in "right-to-left" code - maps, greps, modifier-for - and there, again, I look to name a variable if I'm going to be using it several times:

# different $_ on left and right, but I find this perfectly clear $sum += $_ for /(\d)/g; # or my @saints = grep $_->is_saint, @users; # or my @users = map { my $name = $_; is_god($name) ? find_with_sacrifice($name, $spare_user) : is_saint($name) ? find_with_relic($name, $relic) : $spare_user ? find_user($name) : do { # save for later $spare_user = find_user($name); () } } @names;

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others goofing around in the Monastery: (2)
As of 2024-04-20 05:31 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found