如何在其他内容中使用given(){}?

Eri*_*sum 3 perl

我试图以动态方式传递参数.我想使用Perl函数given(){},但出于某种原因我不能在其他任何东西中使用它.这就是我所拥有的.

print(given ($parity) {
   when (/^None$/) {'N'}
   when (/^Even$/) {'E'}
   when (/^Odd$/)  {'O'}
});
Run Code Online (Sandbox Code Playgroud)

现在我知道我可以在此之前声明一个变量并在print()函数内部使用它,但我正在尝试使用我的代码更清洁.同样的原因我不使用复合if-then-else语句.如果它有助于这里的错误

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.
Run Code Online (Sandbox Code Playgroud)

ike*_*ami 8

你不能把语句放在表达式中.

print( foreach (@a) { ... } );  # Fail
print( given (...) { ... } );   # Fail
print( $a=1; $b=2; );           # Fail
Run Code Online (Sandbox Code Playgroud)

虽然do可以帮助你实现这一目标.

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

但说真的,你想要一个哈希.

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

print($lookup{$parity});
Run Code Online (Sandbox Code Playgroud)

甚至

print(substr($parity, 0, 1));
Run Code Online (Sandbox Code Playgroud)

  • +1即将提出相同的建议. (2认同)