我想将参数传递给可能仅具有预定义值的方法。
method send-http($url, $http_method) { .... }
我应该创建一个枚举来传递$http_method
吗?如果是这样,怎么办?
或者Perl 6在Ruby中有类似符号的东西吗?
如@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.