momo zone

调核人的blog

perl constant

在perl中使用constant编译指示允许使用常量。常量顾名思义就是在整个程序的执行过程中,变量的值不会发生变化。如果在编写程序的时候, 你能够确定哪些变量的值不在发生变化,你可以使用use constant的方法来定义常量。下面就是标量常量,列表常量,hash常量的使用方法。

Scalar constant

use constant COUNT = > 100;
print COUNT ;

可以发现'COUNT'不需要在前面加'$',也就是说constant标量的使用是一个特殊的语法。

List constant


use constant WEEKDAYS = > qw (
        Sunday Monday Tuesday Wednesday Thursday Friday Saturday
);
print "Today is ", (WEEKDAYS) [1], ".\n"; 

奇葩的语法,'WEEKDAYS'必须用括号括起来。如果直接这样引用会有问题:
print (WEEKDAYS)[1];
因为print是个函数,WEEKDAYS的括号会给print用。也就语法错误了。正确的写法是这样:
print ((WEEKDAYS)[1]);

Hash constant
use constant WEEKABBR = > {
       ‘Monday’ = > ‘Mon’,
       ‘Tuesday’ = > ‘Tue’,
       ‘Wednesday’ = >’Wed’,
       ‘Thursday’ = > ‘Thu’,
       ‘Friday’ = >’Fri’ )
 %abbr = WEEKABBR;
 $day = ‘Wednesday’;
 print “The abbrevaiation for $day is ”, $abbr { $day };

和前面的语法又不一样了,WEEKABBR必须明确赋给一个hash变量才能在后面引用。
Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: