develooper Front page | perl.perl5.porters | Postings from April 2009

Re: feature 'switch' as an expression?

Thread Previous | Thread Next
From:
Michael G Schwern
Date:
April 29, 2009 14:01
Subject:
Re: feature 'switch' as an expression?
Message ID:
49F8BFF7.1000501@pobox.com
Alberto Simões wrote:
> Mark Mielke wrote:
>> Hakim Cassimally wrote:
>>> I wanted to be able to write:
>>>
>>>     my $x = given ($blah) {
>>>         ....
>>>         default { 'foo' }
>>>        }
>>>
>>> ...
>>> Is there a way to work around this limitation?
>>> And would it be worthwhile me submitting a docpatch to perlsyn?
>>>   
>> Seems like along that path would lie:
>>
>>    my $x = if ($blah) { ... } else { 'foo' };
>>
> 
> For the if construct you can always wrap it into an eval:
> 
>   my $x = eval { if ($blah) { ... } else { 'foo' }; }

Or a do block.  Oh god, that works!  I suspect its a side effect of Perl
compiling if/else into some sort of || conditionals.  while() and foreach()
don't do that.


> Not sure if it works for switch (didn't try).

It doesn't.  While I did have that slight taste of vomit in my mouth when I
think about it, I also think about why I write this:

    my $foo = cond1 ? first   :
              cond2 ? second  :
              cond3 ? third   :
                      default ;

instead of this:

    my $foo;
    if(    cond1 ) { $foo = "first"   }
    elsif( cond2 ) { $foo = "second"  }
    elsif( cond3 ) { $foo = "third"   }
    else           { $foo = "default" }

not just because its more concise, but because it clearly shows that the
purpose is an assignment and will (should) have no other side effects.

given/when has no analog to the ternary op.  Maybe it doesn't need one:

  my $foo = given($blah) {
     when(cond1) { "first"   }
     when(cond2) { "second"  }
     when(cond3) { "third"   }
     default     { "default" }
  };

That's pretty cool.

So +1 to making given/when return the last evaluated expression.


-- 
Robrt:   People can't win
Schwern: No, but they can riot after the game.

Thread Previous | 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