例:
创建文件 test.txt
内容如下:
The Rock|Cheer|Rock Bottom
Triple H|Boo|Pedigree
Stone Cold|Cheer|Stone Cold Stunner
我们通过下面的代码就能简单的打开文,打印文件:
$data_file="test.txt";
open(DAT, $data_file) || die("Could not open file!");
@raw_data=<DAT>;
print "@raw_data";
close(DAT);
但是怎么进行行操作呢,下面的例子中我们就能知道,其实很简单:
使用:
foreach 进行按行取值
foreach $wrestler (@raw_data)
{
print $wrestler;
}
其中:wrestler很任意;
写操作:
打开文 :
$sitedata="websites.cgi";
open(DAT,">>$sitedata") || die("Cannot Open File");
print DAT "Mysite/|http://www.mysite.com/|My website/n";
close(DAT);
写入数据:
$sitename="Mysite";
$siteurl="http://www.mysite.com";
$description="My website";
$sitedata="websites.cgi";
open(DAT,">>$sitedata") || die("Cannot Open File");
print DAT "$sitename/|$siteurl/|$description/n";
close(DAT);
用户锁文件 :
需要在脚本头部引:
use Fcntl;
原型为:
flock(HANDLE, CONSTANT);
例:
$sitename="Mysite";
$siteurl="http://www.mysite.com";
$description="My website";
$sitedata="websites.cgi";
open(DAT,">>$sitedata") || die("Cannot Open File");
flock(DAT, LOCK_EX);
print DAT "$sitename/|$siteurl/|$description/n";
close(DAT);
文件定位:
在脚本头部引用:
use Fcntl qw(:flock :seek);
Value | Location |
---|---|
SEEK_SET | Beginning of the file |
SEEK_CUR | Current position in the file |
SEEK_END | End of the file |
例:
use Fcntl qw(:flock :seek);
函数原型:
seek(HANDLE, OFFSET, LOCATION);
$sitename="Mysite";
$siteurl="http://www.mysite.com";
$description="My website";
$sitedata="websites.cgi";
open(DAT,">>$sitedata") || die("Cannot Open File");
flock(DAT, LOCK_EX);
seek(DAT, 0, SEEK_END);
print DAT "$sitename/|$siteurl/|$description/n";
close(DAT);
其它操作:
判断文件是否存在:
if (-e "filename.cgi")
{
#proceed with your code
}
其它测试符号:
Readable: -r
Writable: -w
Executable: -x
目录操作:
opendir(IMD, "/home/yourname/www/images/") || die("Cannot open directory");
读取DIR
@thefiles= readdir(IMD);
注意这里返回的是一个数组,
可以用foreach读取
foreach $f (@thefiles)
对文件过滤可以使用
unless ( ($f eq ".") || ($f eq "..") )