在本章将要学习:(1)system()函数 (2)捕获输出 (3)代码的移植性

一、system()函数

      若要运行非perl的命令,最简单的方法是使用system()函数。system()函数能够暂停perl程序,运行外部命令,接着在运行你的perl程序。

     system("ls -l") ;system("dir /w")

     system()函数允许你使用命令提示符向你提供的命令解释程序的特性,因为perl的system命令能够调用一个shell或cmd。这样就能够在UNIX下执行重定向、管道传输和后台操作等任务。

    system("sort $f | lp");system("xterm &");

二、捕获输出

      system函数有一个很小的不足,它没有提供一个好的方法来捕获命令的输出,并将它送往perl进行分析。可以使用迂回的方式进行这项操作,例如:

      system("dir > outfile");

      open(OF,"outfile");

      @data=<OF>;

      close(OF);

这个方法很麻烦,还可以用反引号括起来的任何命令均由perl作为外部命令运行

      $directory=`dir`;

在上面这个代码段中,运行的是dir命令,其输出在$directory中捕获。

      @dir=`ls -l`;
       $i=0;
       foreach (@dir) {
           print "$i ", $_, "\n";
            $i++;
   }

在上面这个代码中,@dir的输出在foreach中循环处理,每次处理一行。

 perl参与管道运行的方法是将管道视为既可以读取也可以写入的文件,使用open()函数来实现。

   open(RH,"ls -l | sort |") || die "Cannot open file: $!\n";

在上面这个代码中,open函数打开一个管道,以便从ls -l | sort读取数据。

   open(RH,"| more") || die "Cannot open file: $!\n";

在上面代码中,open函数打开了一个管道,以便将数据写入more命令。输出到RH文件句柄的所有内容均被more缓存。

三、可移植性入门

编写“到处均可运行的”代码时遵循的原则:

 (1) 始终使警告特性处于打开状态,并使用use strict命令。

 (2) 始终都要检查来自系统请求的返回值。例如应该使用open || die

 (3) 输出表义性强的出错消息。

 (4) 使用perl的内置函数,执行你要用system函数或反括号。

 (5) 将依赖系统执行的操作(文件I/O,进程控制)封装在函数中,检查以确保这些操作受当前操作系统的支持。

perl有一个特殊的变量$^O,这个变量包含程序运行时在的操作系统结构,例如在windows下,它包含字符创“MSWin32”。在UNIX下,它包含“linux”。

use strict;
if ($^O eq 'MSWin32') {
   my(@dir,$free);
   @dir=`dir`;
   $free=$dir[$#dir];
   $free =~ s/.*([\d,]+) \w+ free/$1/;
   $free =~ s/,//g;
   print "$free\n";
} elsif ($^O eq 'linux') {
   my(@dir,$free);
   @dir=`df -k`;
   $free=(split(/\s+/,$dir[$#dir]))[3];
   $free=int($free/1024);
   print "${free}M\n";
} else {
   warn "Cannot determine free space on this machine\n";
}

也可以封装的函数中,以便以后随时可以调用

sub freespace {
  my(@dir,$free);
  if ($^O eq 'MSWin32') {
   @dir=`dir`;
   $free=$dir[$#dir];
   $free =~ s/.*([\d,]+) \w+ free/$1/;
   $free =~ s/,//g;
} elsif ($^O eq 'linux') {
   my(@dir,$free);
   @dir=`df -k`;
   $free=(split(/\s+/,$dir[$#dir]))[3];
   $free=int($free/1024);
} else {
   warn "Cannot determine free space on this machine\n";
}
  return $free;
}