您的位置:首页 >> Web开发 >> CGI技术 >> 正文
CGI技术 RSS
 

Perl的经典用法

http://www.rdxx.com 06年04月21日 07:27 网海之贝 我要投稿

关键词: Perl


or die "unable to append to $filename: $!";


如果在open() 和出错信息中都写了文件的全名,你会冒改变了open() 的风险,使得出错信息不合时宜或不正确。

  # 下面会出现虚假的出错信息

open(FH, "</var/run/file.pid")

    or die "Can't open /var/log/file.pod for writing : $!";

用 Sysopen()进行更多的控制
为了更好的控制文件的打开方式,可以使用 sysopen() 函数:

use Fcntl;

  sysopen(FH, $filename, O_RDWR|O_CREAT, 0666)

    or die "Can't open $filename for reading/writing/creating : $!";


函数 sysopen() 带有四个参数,第一个是同open()函数类似的文件句柄参数,第二个参数是不带模式信息的文件名,第三个参数是模式参数,由Fcntl 模块提供的逻辑OR运算组合起来的常数构成,第四个参数(可选),为八进制属性值(0666表示数据文件, 0777表示程序)。如果文件可以被打开,sysopen() 返回true,如果打开失败,则返回false。

不同于open()函数,sysopen()不提供模式说明的简写方式,而是把一些常数组合起来,而且,每个模式常数有唯一的含义,只有通过逻辑OR运算才能将它们组合起来,你可以设置多个行为的组合。

O_RDONLYRead-only

  O_WRONLY     Write-only

  O_RDWR Reading and writing

  O_APPEND Writes go to the end of the file

  O_TRUNC Truncate the file if it existed

  O_CREAT Create the file if it didn't exist

  O_EXCLError if the file already existed (used with O_CREAT)


当你需要小心行事的时候,就使用sysopen() 函数,例如,如果你打算添加内容到文件中,如果文件不存在,不创建新文件,你可以这样写:

sysopen(LOG, "/var/log/myprog.log", O_APPEND, 0666)

or die "Can't open /var/log/myprog.log for appending: $!";

读入单个记录
有一个容易的方法读入filehandles:用 <FH> 操作符。在标量内容下,它返回文件中的下一个记录,或者返回未定义出错信息。我们可以使用它来把一行读入到一个变量中:

$line = <FH>;

  die "Unexpected end-of-file" unless defined $line;

在循环语句中,我们可以这样写:

  while (defined ($record = <FH>)) {     # long-winded

    # $record is set to each record in the file, one at a time

共7页  1 2 3 4 5 6 7


 
 
标签: Perl 打印本文
 
 
  热点搜索
 
 
 



Valid XHTML 1.0 Transitional
Copyright ©2005 - 2008 Rdxx.Com,All Rights Reserved
收藏本页
收藏本站