您的位置:首页 > 其它

Perl语言入门(第五版) 读书笔记(二)---输入与输出、文件读写

2013-12-13 15:54 555 查看
第五章 输入与输出

1. 标准输入<STDIN>

chomp($line=<STDIN>);

while(defined($line=<STDIN>)) {}

foreach(<STDIN>){print $_;}

2. 钻石操作符<> 默认采用@ARGV数组作为输入,如果为空则改为<STDIN>

3. 调用参数列表@ARGV

4. printf() 格式化输入,print/printf不指定流时默认为STDOUT

use 5.010;

say "Hello!"; #say和print一样,但是会自动增加换行符

5. 打开文件句柄

open FH,"$file"; #read, default方式

open FH,"<$file"; #read

open FH,">$file"; #write

open FH,">>$file"; #append

open FH,"+<$file"; #read-update

open FH,"+>", "/root/file"; #write-update

open FH,"+>>", $file; #append-update

open FH, "| cat >hello"; #open pipe

close FD;

5. 用die处理严重错误,die可以输出信息并终止程序

warn和die用法一样,但是不会终止程序

6. 使用文件句柄

1)文件读取的3中方法

按行读,存入标量

while (<FILE>) { print; }

按行读,存入数组

@array = <FILE>;

读入整个文件 ,存入标量

$string = do { local $/; <FILE>; };

2)读文件实例

open (EP,"/etc/passwd");

while (<EP>)

{

chomp;

print "I saw $_ in the password file!\n";

}

3)读写文件实例

open(IN,$a) || die "cannot open $a for reading: $!";

open(OUT,">$b") || die "cannot create $b: $!";

while ($line = <IN>)

{

print OUT $line;

}

close(IN) ;

close(OUT) ;

7. 复用标准文件句柄

select STDERR; #select能改变默认的文件句柄

复用文件句柄时,perl会自动关闭原来的文件句柄。

if (! open STDERR, ">> /var/error.log") #将错误信息写到自定义文件中

{

die "Can't open error log for append:$!";

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: