develooper Front page | perl.perl5.porters | Postings from August 2012

Early return from expression

Thread Next
From:
John Wiersba
Date:
August 27, 2012 07:07
Subject:
Early return from expression
Message ID:
1346076421.24389.YahooMailNeo@web161501.mail.bf1.yahoo.com
I have long thought that this would be a nice feature to have, similar in use to return(), but for expressions.  Some syntax like:
   value EXPR
   value

to cause an expression block to produce a value without having to nest it inside some kind of conditional.  Similar to return(), if it were used without specifying a value, it would produce either undef or an empty list value, depending on if it were used in list context or not.

Currently, this type of feature can be simulated by having the expression be a call to a function, and then using return() in the function.  But it would be nice to avoid creating and calling a function in many simple cases.  Another way to do this currently, besides a nested if-else expression is to use the ternary ?: expression.  But that suffers from readability and comprehensibility, the same way nested if-else expressions suffer from readability and wordiness.

I love how perl's statement modifiers (e.g. STMT if COND) allow some compression of code while maintaining (or enhancing) readability.  Similarly, next/last/redo allow for the expression of complicated logic without needing to introduce extra booleans or use deeply nested if-else statements.  And short-circuiting boolean expressions allow easily understood logic without spelling everything out with if-else expressions.  Some kind of early exit from a complicated expression (such as with a "value" keyword) would also improve readability without any downsides, I believe.


Here's an example of what I have in mind:

old way:

   map {
      if (COND1) {
         VALUE1

      } elsif (COND2) {
         if (COND3) {
            VALUE2

         } else {
            VALUE3

         }

      } else {
         VALUE4

      }

   } LIST;

new way:
   map {
      value VALUE1 if COND1;
      value VALUE4 unless COND2;
      value VALUE2 if COND3;
      value VALUE3;           # or simply: VALUE3

   } LIST;
Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About