perl文件操作

简介: 打开、关闭文件   open (filevar, filename)     filevar为文件句柄,或者说是程序中用来代表某文件的代号    filename为文件名,其路径可为相对路径,亦可为绝对路径 open(FILE1,"file1");open(FILE1, "/u/jqpublic/f...


打开、关闭文件
   open (filevar, filename)
    filevar为文件句柄,或者说是程序中用来代表某文件的代号
    filename为文件名,其路径可为相对路径,亦可为绝对路径
open(FILE1,"file1");
open(FILE1, "/u/jqpublic/file1");


   打开文件时必须决定访问模式
open(FILE1,"file1");
 read
 
open(outfile,">outfile");
 write写模式将原文件覆盖,原有内容丢失
open(appendfile, ">>appendfile");
 append
 

  
    open的返回值用来确定打开文件的操作是否成功,成功时返回非零值,失败时返回零:
if (! open(MYFILE, "myfile")) {
    die ("cannot open input file file1\n");
    }
 
 open (MYFILE, "file1") || die ("Could not open file");


    close (MYFILE);

    例子.读文件并显示
#!/usr/bin/perl

&gotest("/home/macg/perltest/gogo");
&gotest("/home/macg/www/index.html");
&gotest("jk");

sub gotest{
my(@tmp)=@_;
open (MYFILE, $tmp[0]) || die ("Could not open file");
@array = <MYFILE>;      此句不是读一行,而是读整个文件
foreach (@array) {
 print $_;
   }
close(MYFILE);
}
 
[macg@localhost perltest]$ ./tip.pl
kkkkk               第一个文件gogo读出

第二个文件index.html读出
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<frameset rows=20%,*>
  <frame src="title.html" frameborder="no" scrolling="no">
  <frameset cols=30%,*>
    <frame src="index-left.htm" frameborder="no" name="left">
    <frame src="main-right.html" frameborder="no" name="right">
  </frameset>
</frameset>

第三个文件jk不存在,程序走die语句
Could not open file at ./tip.pl line 9
 

 
    打开管道文件--------操作非常简单,就是以带管道符号的命令作为文件名字符串
    执行一个管道命令
    假设管道命令创建一个临时文件
    再OPEN这个临时文件到句柄
[macg@localhost perltest]$ vi tip.pl
#!/usr/bin/perl

&gotest("ls -l |");

sub gotest{
my(@tmp)=@_;
open (MYFILE, $tmp[0]) || die ("Could not open file");
@array = <MYFILE>;
foreach (@array) {
 print $_;
      }
close(MYFILE);
}
 
[macg@localhost perltest]$ ./tip.pl
total 16
-rw-rw-r--  1 macg macg   6 Mar 16 13:06 gogo
-rwxrwxr-x  1 macg macg 192 Mar 17 16:53 tip.pl
 

    读文件
$line = <MYFILE>;
 读一行
并把文件指针向后移动一行
 
@array = <MYFILE>;
 读全部
文件的每一行(含回车符)为@array的一个字符串元素
 
最简单的显示文件 @array = <MYFILE>;      一次读整个文件,读入一个字符串数组

foreach (@array) {            再打印字符串数组的每一个元素(每一行)
 print $_;
      }
 
[macg@localhost perltest]$ ./tip.pl
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">

<frameset rows=20%,*>
  <frame src="title.html" frameborder="no" scrolling="no">
  <frameset cols=30%,*>
  </frameset>
</frameset>
 
my($line);
while ($line=<MYFILE>) {循环读一行,读不出就为NULL(0)
 print $line; 
 }
 


    $line =<STDIN> ;      从键盘读一行
,类似C的gets();
 

    chomp 函数,截去变量尾端的\n换行,常与键盘输入合用,方法有二種:
1    $yourans=<STDIN>;
      chomp $yourans;
 
2    chomp ($yourans=<STDIN>);
 


   注意:一定不要用while (chomp($line=<MYFILE>)),因为chomp总是返回0值,和while($line=<MYFILE>)是不同的
while($line=<MYFILE>){
chomp($line);  把 chomp放在循环里边
…
} 
 
 

   <> 和 <STDIN> 的区别
先说相同点:都支持标准输入读取
不同点:<> 可以将输入定向到命令行参数
vi  readfile.pl
#! /usr/bin/perl
while (<>) {
    print;
}
 
./readfile.pl index.html    就是读取第一个命令行参数所指的文件
./readfile.pl               如果不带任何参数执行,就是由标准输入STDIN读取
 

 
   写文件     print/printf  句柄 (字串);
open(OUTFILE, ">outfile");
print OUTFILE ("Here is an output line.\n");
 
print STDERR ("File file1 exists.\n");
print STDOUT ("File file1 exists.\n");
 


    最简单的文件COPY
#!/usr/bin/perl
&gotest("ls -l |","test");

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

[macg@localhost perltest]$ ./tip.pl
/home/macg/perltest/dd           全路径删除

[macg@localhost perltest]$ ls
test  testdir  tip.pl


rename("原文件名", "新名");
#!/usr/bin/perl
&gotest("gogo","dd");

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  
 
 


    文件copy命令              必须先use模块File
#!/usr/bin/perl

chomp($file=<>);
chomp($file2=<>);
&gotest($file,$file2);

sub gotest{
my(@tmp)=@_;
use File::Copy;     在perl主目录下查找File/Copy.pm

copy($tmp[0], $tmp[1]);
}  
 
[macg@localhost perltest]$ ./tip.pl
test
newtest
[macg@localhost perltest]$ ls
newtest  test  testdir  tip.pl 


 
[root@localhost perltest]# ls -F /usr/lib/perl5/5.8.6/File
Basename.pm  CheckTree.pm  Compare.pm  Copy.pm  DosGlob.pm  Find.pm  Path.pm  Spec/  Spec.pm  stat.pm  Temp.pm


   目录操作
  chdir("testdir") || die "$!";
  mkdir($dir, 0755)  || die "$!";
  rmdir("testdir") || die "$!";
#!/usr/bin/perl

chomp($directory=<>);
chomp($choice=<>);
&gotest($directory,$choice);

sub gotest{
my(@tmp)=@_;

if($tmp[1]) {
mkdir($tmp[0], 0755)  || die "$!";
   } else {
rmdir($tmp[0]) || die "$!";
     }
}
 
[macg@localhost perltest]$ ./tip.pl
newdir
1
[macg@localhost perltest]$ ls -F
newdir/  newtest  test  testdir/  tip.pl*  
[macg@localhost perltest]$ ./tip.pl
testdir
0
Directory not empty at ./tip.pl line 13, <> line 2
rmdir的die信息
 

   改变文件属性和所属(需在root下才能起作用。换句话说,这是必须在ROOT下执行的PERL语句)
chmod(0755, "file1.txt", "file2.txt"); 
 
$uid=500;
$gid=500;
chown($uid, $gid, "file1.txt", "file2.txt");  
 

相关文章
|
存储 SQL 监控
数据中台架构解析:湖仓一体的实战设计
在数据量激增的数字化时代,企业面临数据分散、使用效率低等问题。数据中台作为统一管理与应用数据的核心平台,结合湖仓一体架构,打通数据壁垒,实现高效流转与分析。本文详解湖仓一体的设计与落地实践,助力企业构建统一、灵活的数据底座,驱动业务决策与创新。
|
11月前
|
人工智能 自然语言处理 监控
GEO优化专家尹邦奇拆解:GEO哪套方法靠谱
在AI搜索时代,GEO(生成式引擎优化)正取代传统SEO,核心是让内容被AI理解、引用并成为答案源。本文深度解析靠谱GEO的三大标准:清晰AI理解逻辑、结构化实操路径、平台验证数据,并重点推荐经多模型验证的“尹邦奇答案架构师+GEO五步法”。(239字)
|
11月前
|
人工智能 安全 Shell
在 Moltbot (Clawdbot) 里配置调用阿里云百炼 API 完整教程
Moltbot(原Clawdbot)是一款开源AI个人助手,支持通过自然语言控制设备、处理自动化任务,兼容Qwen、Claude、GPT等主流大语言模型。若需在Moltbot中调用阿里云百炼提供的模型能力(如通义千问3系列),需完成API配置、环境变量设置、配置文件编辑等步骤。本文将严格遵循原教程逻辑,用通俗易懂的语言拆解完整流程,涵盖前置条件、安装部署、API获取、配置验证等核心环节,确保不改变原意且无营销表述。
4487 6
|
12月前
|
存储 NoSQL Shell
Redis集群部署指南
本章为CentOS7下Redis集群实战教程,涵盖单机安装、主从复制、哨兵集群及分片集群搭建。通过详细步骤实现多实例部署,掌握高可用与数据分片核心技术,助力构建稳定高效的Redis分布式系统。(238字)
|
运维 网络协议 搜索推荐
内核网络小白之故障寻踪记
本文记述了一次由 skb(socket buffer)异常导致的内核故障排查过程。
822 12
|
5G Linux 网络架构
一款简单纯粹的在线测速工具 - 免费开源 | 基于LibreSpeed开源项目开发
龙腾测速网是由龙毅基于开源项目LibreSpeed美化开发的免费在线测速工具,界面简洁、功能纯粹,支持所有现代浏览器。提供上传下载速度、延迟、抖动等网络信息,测速结果精准稳定,可自动保存并导出历史记录。适用于Windows、macOS、Linux系统,无需安装,打开网页即可使用,是判断网络问题的实用工具。项目完全开源,可自由二次开发。
4008 0
|
网络协议 关系型数据库 Linux
Linux系统命令大全
Linux系统命令大全
350 0
|
机器学习/深度学习 人工智能 自然语言处理
Magma:微软放大招!新型多模态AI能看懂视频+浏览网页+UI交互+控制机器人,数字世界到物理现实无缝衔接
Magma 是微软研究院开发的多模态AI基础模型,结合语言、空间和时间智能,能够处理图像、视频和文本等多模态输入,适用于UI导航、机器人操作和复杂任务规划。
1236 2
|
应用服务中间件
15-Filter 过滤器2
15-Filter 过滤器2
244 0
|
消息中间件 负载均衡 Kafka
Kafka学习---消费者(分区消费、分区平衡策略、offset、漏消费和重复消费)
Kafka学习---消费者(分区消费、分区平衡策略、offset、漏消费和重复消费)
3792 2