gpt4 book ai didi

perl - 如何将枚举类型验证为 Perl 子例程参数?

转载 作者:行者123 更新时间:2023-12-01 09:10:57 25 4
gpt4 key购买 nike

建立Does Perl have an enumeration type? ,我如何执行动态类型检查(或静态类型检查,如果 use strict 能够这样做)我的子例程参数正在获取正确的枚举类型?

package Phone::Type;

use constant {
HOME => 'Home',
WORK => 'Work',
};

package main;

sub fun
{
my ($my_phone_type_enum) = @_;
# How to check my_phone_type_enum, is either Phone::Type->HOME or Phone::Type->WORK or ... but not 'Dog' or 'Cat'?
}

fun(Phone::Type->HOME); # valid
fun(Phone::Type->WORK); # valid
fun('DOG'); # run-time or compile time error

最佳答案

这是一种方法:

#!/usr/bin/perl

package Phone::Type;

use strict;
use warnings;

use constant {
HOME => 'Home',
WORK => 'Work',
};

package main;

use strict;
use warnings;

sub fun {
my ($phone_type) = @_;
Phone::Type->can( $phone_type )
or die "'$phone_type' is not valid\n";
}

fun('HOME'); # valid
fun('WORK'); # valid
fun('DOG'); # run-time or compile time error
__END__

C:\Temp> dfg
'DOG' is not valid

关于perl - 如何将枚举类型验证为 Perl 子例程参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1043138/

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