How do I use given(){ } inside something else?

perl

Solution

You can't put statements inside expressions.

print( foreach (@a) { ... } );  # Fail
print( given (...) { ... } );   # Fail
print( $a=1; $b=2; );           # Fail

Though `do` can help you achieve that.

print( do { foreach (@a) { ... } } );  # ok, though nonsense
print( do { given (...) { ... } } );   # ok
print( do { $a=1; $b=2; } );           # ok

But seriously, you want a hash.

my %lookup = (
   None => 'N',
   Even => 'E',
   Odd  => 'O',
);

print($lookup{$parity});

Or even

print(substr($parity, 0, 1));

Problem

I am trying to pass parameters in a dynamic way. I'd like to use the Perl function `given(){}`, but for some reason I cannot use it inside of anything else. Here's what I have. ``` print(given ($parity) { when (/^None$/) {'N'} when (/^Even$/) {'E'} when (/^Odd$/) {'O'} }); ``` Now I know I can declare a variable before this and use it inside of the `print()` function, but I'm trying to be cleaner with my code. Same reason I don't use compounded `if-then-else` statements. If it helps here's the error ``` syntax error at C:\Documents and Settings\ericfoss\My Documents\Slick\Perl\tests\New_test.pl line 22, near "print(given" Execution of C:\Documents and Settings\ericfoss\My Documents\Slick\Perl\tests\New_test.pl aborted due to compilation errors. ```

Original source