十分钟学perl够用(客服MM都懂了)
perl
2017-03-11

零基础,perl语言,10分钟入门

  1. Hello,World

    #!/usr/bin/perl -w
    print ("hello,world!\n");
    #print "hello,world!\n";
    

    说明:

    • (1)第一行指定解释器,-w参数表示提示警告(或者使用use strict命令,执行更严格的检查);
    • (2)第二行输出hello, world!;
    • (3)如果习惯c的函数方式,print的参数可以打括号;
    • (4)第三行是注释,注释以#打头;
    • (5)如果习惯shell的方式,print的参数可以没有括号;
    • (6)双引号内可以使用转义字符;

    不妨设文件名为helloworld.pm 程序的执行方法为:

    • (1)perl helloworld.pm
    • (2)chmod 755 helloworld.pm && ./helloworld.pm
  2. 常量

    • 2.1 数字
      • (1)Perl内部总按照“双精度浮点数”保存数字并执行运算;
      • (2)0377=>八进制;0xFF=>十六进制;
    • 2.2字符串
      • (1)单引号表示字符串,不转义;
      • (2)双引号表示字符串,转义且解释变量;
    • 2.3字符串操作符
      • (1)拼接操作符:“.”=>拼接字符串;
      • (2)重复操作符:“x”=>一个字符串重复多次;

        #!/usr/bin/perl -w
        print ("hello,"."world!\n");
        print ("hello " x 3);
        

        输出结果是: hello,world! hello hello hello

    最后要说明一点,Perl是弱类型语言,字符串和数字会相互转化,这一点和php一样。

  3. 变量
    • (1)变量以$开头,后接一个标示符;
    • (2)如何用变量获取用户输入? 使用,它获取用户的输入(一般以换行结束),可以使用chomp去除结尾的换行符。

      #!/usr/bin/perl -w
      $count = 0;
      while($count<10)
      {
          chomp($input = );
          print($input);
          $count++;
      }
      
    • (3)未定义变量 未定义的变量会赋予undef值,它既不是数字,也不是字符串; 它有可能被当做数字0使用; 使用define函数可以知道一个变量是否被定义;

      #!/usr/bin/perl -w
      $var = undef;
      print($var);
      if(defined($var))
      {
          print("defined!\n");
      }
      else
      {
          print("undefined!\n");
      }
      $var++;
      print($var);
      

      它的输出是: Useof uninitialized value in print at undef.pm line

      1. undefined!
    • (4)变量的作用域
      • my和our可以指定变量的作用域
      • my指定为局部作用域;
      • our指定为全局作用域(默认为our);

        #!/usr/bin/perl -w
        our $g_one = "global_one\n";
        $g_two = "global_two\n";
        {
        my $local_one = "local_one\n";
        print($g_one);
        print($g_two);
        print($local_one);
        }
        print($g_one);
        print($g_two);
        print($local_one);
        

        输出为: global\_one global\_two local\_one global\_one global\_two Use of uninitialized value in print at our\_my.pm line 13.

  4. 数组与列表
    • 4.1数组 和c的数组使用非常类似:

      $array[0]=”a0″;
      $array[1]=”a1″;
      $array[2]=”a2″;
      
    • 4.2列表 圆括号内的一系列值,构成列表:

      (1, 2, 3)
      (“hello”, 4)
      (“hello”, “world”, “yes”, “no”)
      qw(hello world yes no)
      (1..10)
      

      说明:

      • (1)第一行,列表元素为1,2,3;
      • (2)第二行,列表元素为一个字符串,一个数字;
      • (3)第三行,列表元素为4个字符串,好多引号和逗号啊;
      • (4)第四行,wq操作符,用来建立字符串列表,而不用输入这么多引号和逗号,效果同(3);
      • (5)范围操作符“..”,表示一个范围,从左至右连续加一。 列表的赋值: ($v1, $v2, $v3) = qw(yes i am); 整个列表的引用,=@=操作符:

        @list = qw(yes i am);
        @none = ();
        @huge = (1..5);
        @stuff = (@list, @none, @huge);
        

        pop和push操作符:

      • (1)pop弹出列表末端元素;
      • (2)push向列表末端压入元素; shift和unshift操作符:
      • (1)shift移出列表首部元素;
      • (2)unshift向列表首部压入元素; 列表的输出:
      • (1)列表输出,只输出列表,元素间不含空格;
      • (2)列表的字符串化输出,输出列表,元素间加入空格;
      • (3)foreach控制结果,可以依次取得列表中各个元素

        #!/usr/bin/perl -w
        @list = qw(yes i am);
        @none = ();
        @huge = (1..5);
        @stuff = (@list, @none, @huge);
        $pop_last = pop(@stuff);
        print($pop_last);
        push(@stuff, "hello");
        $shift_first = shift(@stuff);
        print($shift_first);
        unshift(@stuff, "world");
        print(@stuff);
        print("@stuff");
        $element=undef;
        foreach $element (@stuff)
        {
            print("$element!\n");
        }
        

        输出: 5 yes worldiam1234hello world i am 1 2 3 4 hello i! am! 1! 2! 3! 4! hello!

    • 4.3默认变量=$_= 该使用变量的地方,如果省略变量,则会使用默认变量$\_。

      #!/usr/bin/perl -w
      $_="hello,world!";
      print();
      

      输出是: hello,world!

  5. 函数
    • 5.1函数定义与调用
      • (1)定义函数的关键字是sub;
      • (2)函数调用的关键字是&;
      • (3)可用return显示返回,也可用一个数字隐式返回

        #!/usr/bin/perl
        $num=0;
        sub sumAdd
        {
        $num+=1;
        print("$num\n");
        #return $num; # 显示返回
        $num; # 隐式返回
        }
        &sumAdd;
        &sumAdd;
        print(&sumAdd);
        

        执行结果为: 1 2 3 3

    • 5.2函数的参数
      • (1)调用函数时可直接带参数列表;
      • (2)函数定义处使用“默认变量”获取参数列表;

        #!/usr/bin/perl -w
        sub max
        {
        return ($_[0]>$_[1]?$_[0]:$_[1]);
        }
        $big=20;
        $small=10;
        print(&max($big,$small));
        

        输出为: 20

  6. 程序输入输出 上文已经介绍过标准输入,下面介绍其他几种常见的输入输出。
    • 6.1Unix工具输入输出:<> <>提供类似于Unix工具输入输出的功能,它提供的功能能够很好的和cat/sed/awk/sort/ grep等工具结合使用。

      #!/usr/bin/perl -w
      use strict;
      while(<>)
      {
      chomp();
      print("$_!!!\n");
      }
      

      该脚本的功能,是在输入每行后面加上!!!,它几处使用到了默认变量。 不妨设文件名为diamond.pm 不妨设hello.txt中有三行数据,分别是111,222,333 执行步骤:

      • (1)chmod 755 diamond.pm
      • (2)cat hello.txt | ./diamond.pm | cat 输出结果: 111!!! 222!!! 333!!!
    • 6.2格式化输出:printf

      #!/usr/bin/perl -w
      $int_var = 2011;
      $str_var = "hello,world";
      printf("%d\n%s\n",$int_var,$str_var);
      

      输出结果为: 2011 hello,world

    • 6.3文件输入输出 Perl保留了6个文件句柄:STDIN/STDOUT/STDERR/DATA/ARGV/ARGVOUT 上述6.1中的程序还能这么执行: ./diamond.pm out.txt 则输出结果会重定向到out.txt中 输入输出到文件中中,需要打开、使用、关闭文件句柄
      • (1)打开文件句柄:

        open LOG, “>>log.txt”;
        open CONFIG, ”
        
      • (2)关闭文件句柄:

        close LOG;
        close CONFIG;
        
      • (3)使用文件句柄:

        print LOG (“hello,world!\n”);
        print STDERR (“yes i am!\n”);
        while()
        {
        chomp();
        …
        }
        

        也可以使用select关键字:

        print(“to stdout1!”);
        select LOG;
        print(“to log1″);
        print(“to log2″);
        select STDOUT;
        print(“to stdout2!”);
        
        #!/usr/bin/perl -w
        $input_file = "hello.txt";
        $output_file = "out.txt";
        open INPUT, "<$input_file"; open OUTPUT, ">>$output_file";
        while(
        <input type="text">)
        {
        chomp();
        print OUTPUT ("$_!!!\n");
        }
        close OUTPUT;
        close INPUT;
        

        说明:他的功能和之前的diamond.pm是一样的。

  7. 哈希hash
    • 7.1哈希的存取

      $key=”am”;
      $hash_one{“yes”} = 3;
      $hash_one{“i”} = 1;
      $hash_one{$key} = 5;
      print($hash_one{“am”});
      $value = $hash_one{“hello”}; # undef
      
    • 7.2哈希的引用 要引用整个哈希,使用=%=操作符。

      %hash_one = (“hello”,5,”world”,5);
      print ($hash_one{“hello”});
      %hash_two = %hash_one;
      
    • 7.3哈希的松绑 哈希可以转化为键值列表,称为哈希的松绑,转化后不保证键的顺序,但值一定在键的后面。

      #!/usr/bin/perl -w
      %hash_one = ("hello",5,"world",5);
      $hash_one{"yes"} = 3;
      $hash_one{"i"} = 1;
      $hash_one{"am"} = 2;
      @array_one = %hash_one;
      print ($hash_one{"hello"});
      print ("@array_one");
      

      输出结果为: 5 yes 3 am 2 hello 5 world 5 i 1

    • 7.4哈希的反转 建立值对应键的反转哈希。 %hash_reverse = reverse(%hash_one); 只有在键值一一对应的情况下才凑效,否则会有无法预期的覆盖发生。
    • 7.5哈希的美观赋值 哈希的美观赋值使用=>符号。 %hash_one = (“hello”,5,”world”,5,”yes”,3,”i”,1,”am”,2); 上面这种赋值方式很容易搞错,特别是键值都是字符串的时候。

      %hash_one = (
      "hello" => 5,
      "world" => 5,
      "yes"   => 3,
      "i"     => 1,
      "am"    => 2,
      );
      

      美观赋值,是不是看起来更美观,更容易区分哈什的键值呢。

    • 7.6哈希的遍历
      • (1)keys和values函数能返回所有键与值的列表,但列表内顺序不保证。

        @k = keys(%hash_one);
        @v = values(%hash_one);
        
      • (2)each函数能一一遍历哈希,返回键值对,非常适合于while等循环;

        while(($key, $value) = each(%hash_one))
        {
        …
        }
        

        示例代码: `=perl #!/usr/bin/perl -w %hash_one = ( "hello" > 5, "world" => 5, "yes" => 3, "i" => 1, "am" => 2, ); @k = keys(%hash_one); @v = values(%hash_one); print("@k\n"); print("@v\n"); $key = undef; $value = undef; while(($key, $value) = each(%hash_one)) { print("$key=>$value\n"); } 输出结果为: yes am hello world i 3 2 5 5 1 yes=>3 am=>2 hello=>5 world=>5 i=>1

    • 7.7哈希的查询与删除
      • (1)查询一个键是否存在,使用exists函数;
      • (2)删除一个键,使用delete函数;

        #!/usr/bin/perl -w
        %hash_one=(
        "yes" => 3,
        "i" => 1,
        "am" => 2,
        );
        delete($hash_one{"yes"});
        if(exists($hash_one{"yes"}))
        {
        print($hash_one{"yes"});
        }
        

        结果什么也不输出。

  8. 流程控制*(本节可跳过,都是些花哨的用法) 除了各语言常用的if/esle,for,while等流程控制外,Perl还有一些特有的控制语句, 更人性化。
    • (1)unless控制结构 作用效果类似于if not,无效率上提升,只是使表达更自然,代码更容易理解。
    • (2)until控制结构 作用效果类似于while not
    • (3)条件修饰 判断条件可以直接写在语句的后面,以增加可读性(habadog注:这是鬼扯)。 print (“$n”) if $n < 0; $i * 2 until $i > 1024;= &sumAdd($_) foreach @num_list;
    • (4)裸控制结构 只有一个花括号的结构,往往用来限制作用域,在各语言中都很常见。

      {
      $a = 1;
      …
      }
      # $a失效了
      
    • (5)last控制结构 相当于c中的break,立刻终止循环;
    • (6)next控制结构 相当于c中的continue,立刻开始下一次循环;
    • (7)redo控制结构 …独有的,重新开始本次循环;

      while(1)
      {
      # 跳到这里
      print (“hello”);
      redo;
      }
      
  9. 高级特性 神奇的Perl还有正则、module、文件、字符串、智能匹配、进程管理、线程支持等高级 特性,就不在入门手册里介绍了。

如果大伙喜欢,后续发布以上特性的手册。 希望你喜欢上Perl。

其它文章