in reply to Pseudo-switch question

I like switching like this...
my($favorite_color) = ''; # get some kind of input here

print {
      'red'    => sub { 'the color is red.'    }
      'yellow' => sub { 'the color is yellow.' }
      'blue'   => sub { 'the color is blue.'   }
      'null'   => sub { 'I do not know that color' }
   }
      ->{ $favorite_color || 'null' }
--
Tommy Butler, a.k.a. TOMMY

Replies are listed 'Best First'.
Re: Re: Pseudo-switch question
by Tommy (Chaplain) on Jul 23, 2003 at 05:22 UTC

    Oops! Should have checked that code! Curses! Please excuse that poor form; I'm sorry!

    Correction

    my($favorite_color) = ''; # get some kind of input here
    
    print &{{
          'red'    => sub { 'the color is red.'    },
          'yellow' => sub { 'the color is yellow.' },
          'blue'   => sub { 'the color is blue.'   },
          'null'   => sub { 'I do not know that color' }
       }
          ->{ $favorite_color || 'null' }}
    
    
    --
    Tommy Butler, a.k.a. TOMMY
    
Re^2: Pseudo-switch question
by Aristotle (Chancellor) on Jul 23, 2003 at 09:59 UTC
    Concering the correction - you could just append ->(). The null thing doesn't work if you get a key not contained in the hash, though. I'd do something like
    my($favorite_color) = ''; # get some kind of input here my $action = { 'red' => sub { 'the color is red.' }, 'yellow' => sub { 'the color is yellow.' }, 'blue' => sub { 'the color is blue.' }, }->{$favourite_color} || sub { 'I do not know that color' }; print $action->();
    You can arrange the same semantics in different ways, of course. I chose it like this since I was aiming to keep the "default case" together with the rest.

    Makeshifts last the longest.