gpt4 book ai didi

perl - 如何在其他东西中使用 given(){ }?

转载 作者:行者123 更新时间:2023-12-01 09:32:22 27 4
gpt4 key购买 nike

我正在尝试以动态方式传递参数。我想使用 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.

最佳答案

您不能将语句放在表达式中。

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));

关于perl - 如何在其他东西中使用 given(){ }?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13824791/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com