perl 学习日记1(文件操作)

原文:http://blog.chinaunix.net/space.php?uid=9398085&do=blog&id=1677708

打开文件

if (open(TXT,"C:/Documents and Settings/Administrator/桌面/integrate.txt")) {

print "successed!";

}

else {

print "failed.";

exit 1;

}

 

关闭文件句柄

close(TXT); # TXT是句柄名

 

$!返回操作系统的相应出错消息

if (!open(TXT,"C:/Documents and Settings/Administrator/桌面/integrat.txt")){

warn "cannot read integtate: $!";

} else {

print " OK!";

exit 1;

}

$!为“No such file or directory

 

读取文件

open(TXT,"C:/Documents and Settings/Administrator/桌面/integrate.txt") or die "cannot open integrate: $!";

$line = <TXT>;

print $line;

输出为文件的第一行

 

打印整个文件

open(TXT,"C:/Documents and Settings/Administrator/桌面/integrate.txt") or die "cannot open integrate: $!";

while (defined($a = <TXT>)){

print $a;

}

或者使用$_

while (<TXT>){

print $_;

}

w h i l e循环将负责把输入行赋予$_

或者使用

@contents=<TXT>; #文件的每一行作为数组的一个元素

print @contents; #打印整个文件

print $contents[1]; #打印文件的第二行

 

写入文件

open(TXT,">>C:/Documents and Settings/Administrator/桌面/test.txt") or die "cannot open integrate: $!";

if (! print TXT "This entry was written at ",scalar(localtime),"\n"){

warn "Unable to write the test file: $!"; # print完成追加写入

}else {

print "Operation successde!";

}

close(TXT);

open(TXT,"C:/Documents and Settings/Administrator/桌面/test.txt") or die "cannot open integrate: $!";

@new=<TXT>;

print @new;

close(TXT);

 

拷贝文件

open(T1,">>C:/Documents and Settings/Administrator/桌面/test.txt") or die "cannot open integrate: $!";

open(T2,"C:/Documents and Settings/Administrator/桌面/test2.txt") or die "cannot open integrate: $!";

@contents=<T2>;

$a=2011;

print T1 "@contents $a"; # test将被追加写入test2的内容和2011.

close(T1);

close(T2);

或者print T1 <T2>; #效果相同,更为简洁

 

你可能感兴趣的:(学习,职场,perl,休闲)