Perl 6中的枚举或符号

问题描述 投票:4回答:1

我想将参数传递给可能仅具有预定义值的方法。

   method send-http($url, $http_method) { .... }

我应该创建一个枚举来传递$http_method吗?如果是这样,怎么办?

或者Perl 6在Ruby中有类似符号的东西吗?

perl perl6 raku
1个回答
3
投票

如@Christoph所述,您可以使用枚举:

enum Method <GET PUT POST>;
sub http-send(str $url, Method $m) { * }

http-send("http://url/", GET);

您也可以使用类型约束:

sub http-send(str $url, str $m where { $m ∈ <GET HEAD POST> }) { * }

http-send("http://url/", 'GET');

http-send("http://url/", 'PUT');
Constraint type check failed for parameter '$m'

我想您也可以使用多重分派:

multi sub http-send('GET') { * }
multi sub http-send('PUT') { * }
multi sub http-send($m) { die "Method {$m} not supported." }

http-send('GET');

http-send('POST');
Method POST not supported.
© www.soinside.com 2019 - 2024. All rights reserved.