[JaxPM] && usage?

Steve Lane sml at zfx.com
Sat Jan 5 15:53:18 CST 2002


On the jacksonville-pm-list; Jax.PM'er Steve Lane <sml at zfx.com> wrote -

Bill Jones wrote:
> I am wondering about using the short-circuit && operator to execute
> multiple commands should some condition exist.  I ask the list
> their respective opinion(s) about anything good, bad, or ugly
> about &&.  Thx :)
> 
> An example snippet (not -w or strict safe, hell it likely doesn't
> work) -
> 
> while (defined($_ = <DATA>)) {
>          ++$process && chomp;
>          s{\/\*.*} {};  # No C/CSS-like comments...
>          s{^\s+}   {};  # No leading whitespace...
>          s{\s+$}   {};  # No trailing whitespace...
>          ++$empty && next unless length;
> 
>          $curline = $_;
>          &sx_css_not_handled($curline) && next if ($curline =~ /#/);
> 
>          &sx_do_head() && next unless $headdone;
> }

i dunno about good bad or ugly.  but if anyone
else has to maintain lines like

  &sx_css_not_handled($curline) && next if ($curline =~ /#/);

they will curse your name.  there's nothing wrong
with using && and || for conditionals.  a lot of people
prefer them to 'if' for many cases.  but -combining-
&& and if is a definite no-no, if you value readable
and maintainable code.

that said, my version of your code isn't all that different:

while (<DATA>) {
  # the "++$process && chomp;" is bizarre.
  # is $process ever -1?  if not, the condition
  # is always true, so what's its purpose?
  chomp;
  $process++;


  s{/\*.*}  {};  # strip C/CSS-like comments...
  s{^\s+}   {};  # strip leading whitespace...
  s{\s+$}   {};  # strip trailing whitespace...

  !length  and  ++$empty  and   next;

  $curline = $_;

  $curline =~ /#/  and  sx_css_not_handled($curline)  and  next;

  # if sx_do_head() has side effects, i'd prefer
  # doing it and assigning a return value, and then
  # testing that, rather than doing everything
  # in one fell swoop.
  !$headdone  and  sx_do_head()  and next;
}

i won't say that that's the "best" version of the code;
i'm not even sure if it's equivalent; hopefully i didn't
make any mistakes.  but i think it's preferable.
--
Steve Lane <sml at zfx.com>

Jax.PM Moderator's Note:
This message was posted to the Jacksonville Perl Monger's Group listserv.
The group manager can be reached at -- owner-jacksonville-pm-list at pm.org
to whom send all praises, complaints, or comments...




More information about the Jacksonville-pm mailing list