open的返回值用来确定打开文件的操作是否成功,成功时返回非零值,失败时返回零:
if (! open(MYFILE, "myfile")) {
die ("cannot open input file file1\n");
}
open (MYFILE, "file1") || die ("Could not open file");
sub gotest{
my(@tmp)=@_;
open (READFILE, $tmp[0]) || die ("Could not open file");
open (WRITEFILE, ">".$tmp[1]) || die ("Could not open file");
my($line);
while ($line=<READFILE>) {
print WRITEFILE $line;
}
close(READFILE);
close(WRITEFILE);
}
[macg@localhost perltest]$ ./tip.pl
[macg@localhost perltest]$ ls
gogo test tip.pl
[macg@localhost perltest]$ cat test
-rw-rw-r-- 1 macg macg 6 Mar 16 13:06 gogo
-rwxrwxr-x 1 macg macg 297 Mar 17 17:43 tip.pl
上例同时也是一次管道文件的建立,相当于ls –l >test
-e 文件是否存在 -d 目录是否存在
#!/usr/bin/perl
chomp($file=<>);
&gotest($file);
sub gotest{
my(@tmp)=@_;
if (-e $tmp[0]) {
print "file is exist\n";
} else { print "file not found\n"; }
}
[macg@localhost perltest]$ ./tip.pl
gogo
file is exist
[macg@localhost perltest]$ ./tip.pl
kd
file not found
#!/usr/bin/perl
chomp($file=<>);
&gotest($file);
sub gotest{
my(@tmp)=@_;
if (-d $tmp[0]) {
print "directory is exist\n";
} else { print "directory not found\n"; }
}
[macg@localhost perltest]$ ls -F
gogo test testdir/ tip.pl*
[macg@localhost perltest]$ ./tip.pl
kj
directory not found
[macg@localhost perltest]$ ./tip.pl
testdir
directory is exist
if (!-e $file) 如果文件不存在
-r,-w,-x 权限
if (-w $file) {
print "$file 写权限!\n";
}
if (-x $file) {
print "$file 读权限!\n";
}
-z是否为空文件,-s是否非空
if (-z $tmp[0]) {
print "file is empty\n";
}
if ($len= -s $tmp[0]) { -s不仅能判断文件非空,还兼有计算文件大小的工作
print "file length is $len \n";
}
[macg@localhost perltest]$ touch pp
[macg@localhost perltest]$ ./tip.pl
pp
file is empty
[macg@localhost perltest]$ ./tip.pl
gogo
file length is 6
-l 是否为符号链接
-T 是否为文本文件
基本文件操作
删文件
#!/usr/bin/perl
chomp($file=<>);
&gotest($file);
sub gotest{
my(@tmp)=@_;
my($len);
unlink $tmp[0] if -e $tmp[0];
}
[macg@localhost perltest]$ ls
go test testdir tip.pl
[macg@localhost perltest]$ ./tip.pl
go
[macg@localhost perltest]$ ls
test testdir tip.pl
[macg@localhost perltest]$ ls
dd test testdir tip.pl
sub gotest{
my(@tmp)=@_;
rename($tmp[0],$tmp[1]);
}
[macg@localhost perltest]$ ls
gogo pp test testdir tip.pl
[macg@localhost perltest]$ ./tip.pl
[macg@localhost perltest]$ ls
dd pp test testdir tip.pl
取文件属性,共13个属性
#!/usr/bin/perl
chomp($file=<>);
&gotest($file);
sub gotest{
my(@tmp)=@_;
my(@sta)=stat($tmp[0]);
my($j);
for($j=0;$j<13;$j++) {
print "no.$j is $sta[$j] \n";
}
}
[macg@localhost perltest]$ ls
test testdir tip.pl
[macg@localhost perltest]$ ./tip.pl
test
no.0 is 770
no.1 is 809748
no.2 is 33204
no.3 is 1
no.4 is 500 uid
no.5 is 500
no.6 is 0
no.7 is 103 length文件大小
no.8 is 1174127246
no.9 is 1174124625
no.10 is 1174124625
no.11 is 4096
no.12 is 16