Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

perl

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.
like image 610
Eric Fossum Avatar asked Dec 04 '25 17:12

Eric Fossum


1 Answers

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));
like image 58
ikegami Avatar answered Dec 06 '25 07:12

ikegami