Perl文件操作与函数-动态语言程序设计4

Perl文件操作

打开一个文件操作

open(FileVar, filename) ;
FileVar为文件句柄,filename为文件名
打开方式
  • 只读
  • open (FileVar, “<File.txt”);
  • open (FileVar, “>File.txt”);
  • 添加
  • open (FileVar, “>>File.txt”);
判断是否打开成功
if (open(MYFILE, "myfile")) {    # here's what to do if the file opened successfully    }
unless (open (MYFILE, "file1")) {    die ("cannot open input file file1\n");    }
open (MYFILE, "file1") || die ("Could not open file");
die语句语法

关闭文件

close(FileVar);
文件打开以后一定要关闭
$File=“File.txt”;
open(FileVar,”>$File”);

close();

读文件

$line = <FileVar>;    
从文件中读一行,包含回车换行。
成功读取返回1;否则返回 0
$line = <STDIN>;
从屏幕读取用户输入一行
@array = < FileVar >;
把文件的全部内容读入数组,文件的每一行(含回车符)为数组的一个元素。
例子:
While ( $Line=<FileVar> ){
chop($Line);
….
}

写文件

print FileOut "Here is an output line.\n";
往屏幕上输出
 print STDOUT "Here is an output line.\n";
 print "Here is an output line.\n";
例子:
open(FileOut,”>Out.txt”)
print FileOut "Here is an output line.\n";  
close(FileOut)

测试文件状态

-s  文件大小
$Size=-s “file.txt”;
-d  是否为目录
if ( -d “file.txt” ){

}
-e  是否存在
if ( -e “file.txt” ){

}
-r  是否可读
if ( -r “file.txt” ){

}
-w  是否可写
if ( -w “file.txt” ){

}

删除文件
unlink(“File.txt”);
文件改名
rename(“old.txt”,”new.txt”);
建立目录
mkdir(“dir1”);
改变当前路径
chdir(“c:/dir1”);
删除目录
rmdir(“c:/dir1”);
得到当前目录
$CurrentDir=cwd();

取得一个目录下所有文件和目录信息
opendir(DIR,"D:\\Tmp\\");
@File=readdir(DIR);
foreach (@File){
print "Dir1:$_";
}
close(DIR);

子程序

子程序即执行一个特殊任务的一段分离的代码,它可以使减少重复代码且使程序易读。PERL中,子程序可以出现在程序的任何地方。

定义和调用子程序

hello();
sub hello
{
print "hello!";
}

参数传递

@testit=("a","b");
hello("test",@testit);
sub hello
{
my($File,@Array)=@_;
print "$File\n";
print "@Array";
}

变量的有效范围

在函数中定义局部变量
my
sub Function{
my %arrayVar=();
my %mapVar=();
}
local
sub Function{
local @arrayVar=();
local %mapVar=();
Function1();
}
sub Function1}
print “@arrayVar”;
{


查字典子程序:通过子程序重写了练习3
OpenText("dict.txt");
while(1){
 print"input a word(press \'q\' to exit):";
 $Line=;#读取输入字符串
 chomp($Line);
 if($Line eq "q")
 { 
  last; #退出循环
  }
 else{
  search($Line);
 }
}
sub OpenText{
 my ($file)=@_;
 open(In,"$file");
 my $Line;
 while($Line=){
  chomp($Line);
  my @item=split("=>",$Line);
  if(@item==2){
   $hash{$item[0]}=$item[1];
  }
 }
close(In);
}

sub search{
 my($Line)=@_;
 if ( defined $hash{$Line} )
 {  
  print "$hash{$Line}\n";
 }

}

-------------------------------------------------------------------------------------
指令:die参考
语法:die LIST
说明:会把LIST字符串显示出来,并退出程序。常常和 $! 这个代表错误信息变量一起使用。
示例:
open(FILE,"$filename")||die "不能打开文件$!\n; # 如果打开文件失败的话,就会显示出错误的信息,之后再退出程序。

Related Articles

0 评论 :

发表评论

Quote Of The Day