logoalt Hacker News

nekusartoday at 12:09 PM1 replyview on HN

I've never liked cleverness in scripting when clarity costs effectively nothing.

This is one of those clever things, similar to people using perl5 use trinary expressions. Like, are you TRYING to make this obtuse and hard to read?


Replies

garethrowlandstoday at 1:21 PM

The trinary is semantically just an if expression though. Perl inherits C's problem that `if` can't be used in an expression context:

  my $x = if ($cond) { 1 } else { 2 };  # Syntax error
Because of this, Perl introduces a second syntax to plug the gap:

  my $x = $cond ? 1 : 2;
That expression is neither obtuse nor hard to read.

Something like the code below is hard to read:

  my $fee =
    $is_member
        ? ($is_student ? $student_member_fee : $member_fee)
        : ($is_student ? $student_fee        : $standard_fee);
It's equivalent to the following code that uses `if`:

  my $fee;
  if ($is_member) {
      if ($is_student) {
          $fee = $student_member_fee;
      }
      else {
          $fee = $member_fee;
      }
  }
  else {
      if ($is_student) {
          $fee = $student_fee;
      }
      else {
          $fee = $standard_fee;
      }
  }
But ideally you would want to write this:

  my $fee =
    if ($is_member) {
        if ($is_student) {
            $student_member_fee
        }
        else {
            $member_fee
        }
    }
    else {
        if ($is_student) {
            $student_fee
        }
        else {
            $standard_fee
        }
    };
Though, of course, perl5 doesn't allow that.
show 1 reply