就像已知的,其他编程语言类似,PERL解释器,是没有办法自己进行文件读写的,但是呢,可以调用操作系统的文件读写功能,现在我们说下自己的,
文件打开操作使用open命令,后面紧跟的是文件句柄,而后则是打开文件的权限,"<"是只读方式,">"是写方式,如果没有则创建,">>"则是追加在已有文件的最后添加内容
最后则是文件名称,关闭文件使用的是close 后面加的是文件句柄,对于文件的打开或者
#die的含义呢,就是当程序遇到错误时,输出的错误信息,,即就是STDERROR而系统返回的错误信息放在$!当中
#当然若是自己定义的错误,不要加上$!,就行了
if(!open PSW,"<","d:\\a.txt")
{
die "the file open failed $!"
}
else
{
print "the file open succeed with read mode!\n";
}
my $num=1;
while(<PSW>)#行输入操作符,即<>这样的操作是每读取一行将内容放在$_中
{
chomp($_);
print "the ".$num." line is ".$_."\n";
$num++;
}
print "the file close!\n";
close PSW;
if(!open PSW,">>","d:\\a.txt")
{
die "the file open with appened mode failed $!";
}
else
{
print "the file open with appened mode success\n ";
}
print PSW ("HEE\n");
close PSW;
if(!open TXT,"<","d:\\a.txt")
{
print "the file has opened faile in read model with the error:$!"."\n";
return ;
}
#计算每个单词出现的次数
while(<TXT>)
{
if(!defined($stats{$_}))
{
$stats{$_}=1;
}
else
{
$stats{$_}+=1;
}
}
foreach $tmp(keys %stats)
{
print "the words ".$tmp." has appear ".$stats{$tmp}." times\n";
}