>went through the archives about RFC22 "builtin switch statement".
>didn't see any mention of this, thought I'd throw it in there to see
>how it was recieved.

>I was thinking that the switch statement could possibly be expanded
>to also behave as an operator and not just a control statement.

>i.e. the way the trinary conditional operator works:

>my $final = $boolean ? $this_value_if_true : $else_this_value;

>except you could do a case operator:

>my $final = switch ( $val ) {
>          case 0 { $zero_val;}
>          case 1 { $one_val;}
>          case 2 { $two_val;}
>          case 3 { $three_val;}
>     };

>From Camel 3:

    Cascading use of the C<?:> operator can also work for simple
    cases.  Here we use again a C<for> for its aliasing property
    to make repeated comparisons more legible:

        for ($user_color_preference) {
            $value = /red/      ?   0xFF0000  :
                     /green/    ?   0x00FF00  :
                     /blue/     ?   0x0000FF  :
                                    0x000000  ;   # black if all fail
        }

    For situations like this last one, it's sometimes better to build
    yourself a hash and quickly index into it to pull the answer out.
    Unlike the cascading conditionals we just looked at, this one
    scales to an unlimited number of entries, and takes no more time
    to look up the first one than the last.  The disadvantage is that
    you can only do an exact lookup, not a pattern match.  If you
    have a hash like this:

        %color_map = (
            azure       => 0xF0FFFF,
            chartreuse  => 0x7FFF00,
            lavender    => 0xE6E6FA,
            magenta     => 0xFF00FF,
            turquoise   => 0x40E0D0,
        );

    Then exact string lookups run quickly:

        $value = $color_map{ lc $user_color_preference } || 0x000000;

    Even complicated multi-way branching statements (with each case
    involving the execution of several different statements) can be
    turned into fast lookups.  You just need to use a hash of references
    to functions.  See L<Chapter ##, References> for how to handle
    those.

I've actually even used this at run-time, such as:

    $value = {
        azure       => 0xF0FFFF,
        chartreuse  => 0x7FFF00,
        lavender    => 0xE6E6FA,
        magenta     => 0xFF00FF,
        turquoise   => 0x40E0D0,
    }->{ lc $user_color_preference } || 0x000000;

I did that because it was more legible and more convenient although
I confess that that's "rather" inefficient compared with a table
that's built only once.  (Convenience and legibility tend to place
higher on my priority list than "efficiency", since convenience ==
human-efficiency. :-)

Now, some built-in syntax thingie would be even more efficient,
since it could all be done at compile time.  I'd have to go read
Damian's switchy paper; I'd be surprised if this weren't there. 

--tom

Reply via email to