Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

Re: A matter of style: how to perform a simple action based on a simple condition?

by halfcountplus (Hermit)
on Sep 26, 2010 at 17:02 UTC ( #862092=note: print w/ replies, xml ) Need Help??

in reply to A matter of style: how to perform a simple action based on a simple condition?

I don't recall ever using the first one:

$var && sub();

But I don't have any problems with it -- it's clear enough.

Generally I prefer to use the second one wherever possible, tho from habit I always put parentheses around the condition:

sub() if ($var);

The only time I use the third one all on one line is for stuff like:

foreach (@ray1) { push @ray2,$_ if ($_<0) }

Or if there is an else beginning the next line.

I don't understand how having the condition to the right of the action could confuse someone -- I don't think about a line's complete meaning until I've read the whole thing anyway, and it's completely commonplace and normative in natural languages to use subordinate clauses which qualify the previous phrase (ie, your mind should not have difficulty with this). However, I'll admit I'd just as soon do this:

if ($var) sub();

Which is normative in most other languages that I use, such as C, but perl does not allow it.

I presume Larry Wall, linguist and C programmer, had some real reason for this "action before condition" structure in perl and I would doubt it has to do with interpreter internals, so perhaps he saw it as adding something meaningful. Which it does: you can tell something about the nature of this statement because of it's limitations:

action if condition

Namely, that action and condition are both singular and there can be no else clause involved. In other words, having the condition terminate the line indicates that nothing further depends upon it's evaluation. So, instead of adding ambiguity or confusion, I would say number two is (potentially) the opposite: it reduces possible ambiguity because the conditions of it's use are more specific. I guess that "potential" depends on how you choose to respond to it.

Replies are listed 'Best First'.
Re^2: A matter of style: how to perform a simple action based on a simple condition?
by james2vegas (Chaplain) on Sep 26, 2010 at 23:38 UTC
    foreach (@ray1) { push @ray2,$_ if ($_<0) }
    doesn't seem to be the best example to use since it is probably better expressed with a map like
    push @ray2, grep { $_ < 0 } @ray1

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (7)
As of 2016-07-01 09:00 GMT
Find Nodes?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...

    Results (409 votes). Check out past polls.