gggggds 发表于 2015-12-28 13:25:51

Perl 学习手札之三: General syntax

  一般性的语法:
  #!/usr/bin/perl
use strict;
use warnings;
main(@ARGV);
sub main
{
    message("This is the template.pl exercise file from Perl 5 Essential Training.");
}
sub message
{
    my $m = shift or return;
    print("$m\n");
}
sub error
{
    my $e = shift || 'unkown error';
    print("$0: $e\n");
    exit 0;
}
  1. write space in perl are: new line, space charactor andtab.
  write space可以放在任意位置, 解释器会自动忽略write space的作用。
  2. semicolon:
  作为一行语句的结束判断符, 不需要加在大括号的后面;
  3. comment:
  #!/usr/bin/perl
# template.pl by Bill Weinman <http://bw.org/contact/>
# Copyright (c) 2010 The BearHeart Group, LLC
#
use strict;
use warnings;
main(@ARGV);
sub main
{
  my $n = shift ||5;
  my $r = factorial($n);
    message("$n factorial is $r");
}
  #factorial(n)
  #return the product of all integers up to and including n
  # computed recursively
  sub factorial{
  my $n = shift or return 0; #return 0 if no n
  if($n>1){ #only compute for n>1
  return $n * factorial($n-1); #recursion
  }else{
  return 1; #return 1 for n =1
  }
  }
sub message
{
    my $m = shift or return;
    print("$m\n");
}
sub error
{
    my $e = shift || 'unkown error';
    print("$0: $e\n");
    exit 0;
}
  我们添加了一个子函数叫做factorial, 并且对main函数进行了修正, 可以看到, 注释在此时的作用: 提示说明子函数的功能;
  另: 还有其他的注释方式, 我们在这里暂时不涉及 ,如__END__来对所有的文件结尾部分进行注释, 和=begin开始到=end结束中间的代码块都是会被注释掉。
  4. General syntax. 概述整个程序的各部分: shabang,use statement, subroutine
页: [1]
查看完整版本: Perl 学习手札之三: General syntax