perl语言中的定义枚举

时间:2022-12-07 03:54:34

perl语言中定义枚举变量和C语言中类似,默认都是从0开始,并依次递增1个单位;
也可以重新自定义枚举变量的起始值,示例如下:

定义枚举变量:

use enum qw(Sun Mon Tue Wed Thu Fri Sat);
# Sun == 0, Mon == 1, etc

use enum qw(Forty=40 FortyOne Five=5 Six Seven);
# Yes, you can change the start indexs at any time as in C

use enum qw(:Prefix_ One Two Three);
## Creates Prefix_One, Prefix_Two, Prefix_Three

use enum qw(:Letters_ A..Z);
## Creates Letters_A, Letters_B, Letters_C, ...

use enum qw(
:Months_=0 Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
:Days_=0 Sun Mon Tue Wed Thu Fri Sat
)
;

测试代码:

print "enum Wed val: ",Wed,"\n" ;
print "enum FortyOne val: ",FortyOne,"\n" ;
print "enum Prefix_Two val: ",Prefix_Two,"\n" ;
print "enum Letters_A val: ",Letters_A,"\n" ;
print "enum Months_Jan val: ",Months_Jan,"\n" ;
print "enum Days_Sun val: ",Days_Sun,"\n" ;

测试结果:

enum Wed val: 3
enum FortyOne val: 41
enum Prefix_Two val: 1
enum Letters_A val: 0
enum Months_Jan val: 0
enum Days_Sun val: 0

更多参考资料:
https://metacpan.org/pod/enum