Perl语言基本语法-动态语言程序设计2

第一个Perl程序
Perl程序的扩展名为 pl
print "Hello world";

程序结构
# the demo program
$str = "hello world";
print "$str/n";
...
Func();
...
sub Func(){
print "this is the function";
}

简单变量类型

变量以$开头

整型 
十进制 $x = 12345;
8进制 $x = 020;(16)
16进制 $x = 0x20; (32)
浮点数 
11.4 、 -0.3 、.3 、 3. 、 54.1e+02 、 5.41e03
字符串
$str = "this is a string";
$str = 'this is a string';


双引号内可以包含转义字符和其他变量
在字符串中包含  $ @ " \ 前面要加转义字符 \

\n    new line
\t     tab


单引号内就是字符本身,单引号支持多行赋值
在字符串中包含  ‘ 前面要加转义字符 \

简单变量的操作符


算术操作符
+, -, *, **, %,  -
整数比较操作符
<, =, >, !=, >=, <=,<=>
赋值操作符
+=.-=,*=,/=,**=,%=,
自增自减操作符
++,--

控制结构

结构块

{
    an expression;
    another expression;
    last expression;
}

if语句

if(expression){
     one expression;
}
if(expression){
    an expression;
    another expression;
    last one;
}then{
     ....
}


if (expression) {
an expression;
another expression;
last one
} elsif (expression) {

} elsif (expression) {

}else{
}

if语句一定需要花括号包含判断之后的语句块,即使只有一句。Then语句也是一样。


除非语句块


unless (expression) {
an expression;
another expression;
last one
}

=?:语句
$foo = ($j < 0)  ?   ( - $j )   :   $j ;
lvalue = expression ? if_true : if_false ;

循环语句(LOOP)

while循环
while ( expression )  {
statements...
}
# must use braces !!!

while ( not expression )  {
statements...
}
for循环
for ( init ; conditional ; re-init )  {
statements...
}

for ($i=0; $i<10; $i++){
print “$i\n”;
}

while (expression) {
bla...
next;
bla...
}
next相当与C/C++,Java中的continue
while (expression) {
bla...
last;
bla...
}
last相当与break



Related Articles

0 评论 :

发表评论

Quote Of The Day