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

时间:2012-12-11 16:53:33

标签: perl

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

print(given ($parity) {
   when (/^None$/) {'N'}
   when (/^Even$/) {'E'}
   when (/^Odd$/)  {'O'}
});

现在我知道我可以在此之前声明一个变量并在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.

1 个答案:

答案 0 :(得分:8)

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

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

虽然do可以帮助您实现这一目标。

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

但严重的是,你想要一个哈希。

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

print($lookup{$parity});

甚至

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