`
weihe6666
  • 浏览: 436131 次
  • 性别: Icon_minigender_1
  • 来自: 深圳
社区版块
存档分类
最新评论

perl-文件读写

    博客分类:
  • Perl
阅读更多
perl-文件读写


打开、关闭文件
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");
分享到:
评论

相关推荐

    Perl开发环境.zip

    - **系统交互**:Perl可以轻松与操作系统进行交互,执行系统命令,读写文件,控制进程等。 对于初学者,了解Perl的基本语法和常用模块是必要的。例如,`if`语句、`for`和`while`循环、数组和哈希数据结构、子程序...

    ActivePerl-x86

    8. **文件和系统交互**:Perl可以轻松地与文件系统交互,如读写文件、创建目录、执行系统命令等。 9. **错误处理和调试**:Perl使用`eval`函数和`die`语句来处理运行时错误,并可以通过` Carp`模块来生成有用的错误...

    perl读写文件.txt

    在linux上perl对文件读写的几种方法 整体读入 逐行读入 写入

    perl文件用法

    - 使用`open`函数打开文件,然后通过`或`&gt;`操作符读写文件。 - `&lt;&gt;`运算符可以逐行读取文件,例如`while () { ... }`。 5. **正则表达式** - Perl是正则表达式的强大工具,可以使用`=~`操作符匹配和替换字符串中...

    mastering-perl-scripts.zip

    3. **文件和目录操作**:Perl提供了丰富的内建函数用于文件和目录的读写、创建、删除等操作,这是系统管理任务中常见的需求。 4. **模块和CPAN**:CPAN(Comprehensive Perl Archive Network)是Perl模块的宝库,...

    使用perl读写文件

    对学习使用Perl操作文件时写的,在开始学习对Perl文件操作时,使用了$_,导致调试了很长时间,现在改正后做笔记到此

    Perl-5.8.6.811-MSWin32-x86

    - 文件和目录操作,如读写文件、遍历目录结构。 - 网络通信,例如HTTP请求、FTP传输。 - 数据库交互,使用DBI模块连接各种数据库系统。 - 系统管理任务,如监控、自动化备份和日志分析。 - 正则表达式匹配和替换,这...

    magic-perl-for-beginner-.rar_magic

    4. **文件和目录操作**:学习如何读写文件、遍历目录,以及文件处理的I/O操作。 5. **正则表达式**:Perl的正则表达式是其标志性特征之一,教程会深入讲解匹配、替换和提取模式的技巧。 6. **模块和CPAN**:介绍Perl...

    perl-文档资料

    在学习这两本书的过程中,你将了解Perl如何处理字符串和数组,如何读写文件,如何使用正则表达式进行模式匹配,以及如何通过子例程和模块来组织代码。此外,你还将学习到如何利用Perl进行系统管理任务,如自动化脚本...

    Perl 将只读文件属性改成可写文件属性 source

    该Perl脚本的主要目的是在指定目录下查找包含特定字符串的所有只读文件,并将这些文件的权限更改为可读写。 ### 2. 参数解析 #### 2.1 参数格式 该脚本接受两个参数: - 第一个参数是需要检查的目录路径。 - 第二...

    perl-Astro-WaveBand-master.rar

    4. **文件I/O**: 处理波段数据需要读写各种文件格式,如FITS(Flexible Image Transport System)、ASCII文本文件等。Perl提供丰富的文件I/O函数,如`open`, `seek`, `print`, 和 `readline`等。 5. **测试框架**: ...

    perl-pocket-ref-5.004.1.pdf

    根据提供的文件信息“perl-pocket-ref-5.004.1.pdf”,这是一份关于Perl 5.004版本的快速参考指南。该文档详细介绍了Perl编程语言的基础语法、变量、运算符、函数等内容,并提供了针对不同应用场景的实用模块介绍。...

    Perl-by-Example.rar_Perl_Perl by Example_beginners_perl example

    Perl提供了丰富的文件和输入/输出(I/O)函数,可以方便地读写文件、处理标准输入输出。例如,下面的代码会读取并打印一个文件的内容: ```perl open(my $fh, ', 'filename.txt') or die "Cannot open file: $!"; ...

    perl读写xml文件

    这篇博客文章“perl读写xml文件”很可能是关于如何在Perl中操作XML文件,包括解析XML内容、提取数据、修改数据以及生成新的XML文件。 Perl提供了多个模块来处理XML,最常用的是XML::Simple和XML::LibXML。XML::...

    Note of Learning Perl--I/O Basics

    **标题:“学习Perl—输入/输出...通过理解文件句柄、文件的打开和关闭、读写操作以及错误处理,我们可以更高效地处理数据输入和输出。在实际编程中,还需要根据具体需求灵活运用这些概念,以实现复杂的数据处理任务。

    manager及perl依赖centos7版.zip

    9. **perl-Config-Tiny-2.14-7.el7.noarch.rpm**:提供简单的配置文件读写功能,方便管理软件配置。 10. **perl-Email-Date-Format-1.002-15.el7.noarch.rpm**:处理电子邮件日期格式的Perl模块,与邮件相关功能有关...

    提供MySQL负载类型、关键统计、慢查询报告等健康信息-Perl-Shell-下载

    本文将深入探讨如何使用Perl和Shell脚本来获取MySQL的负载类型、关键统计信息以及慢查询报告,帮助你更好地理解和优化你的数据库性能。 一、MySQL负载类型 MySQL的负载类型通常包括查询负载、连接负载和I/O负载。...

    Perl培训材料(来自国外专业培训机构)

    再者,Perl的文件操作能力强大,可以方便地读写文件、处理文件句柄和模式匹配。学会使用`open()` 函数打开文件,`和 `&gt;` 操作符进行读写,以及`&lt;&gt;` 用于从输入文件句柄读取行,这些都是基础中的基础。 正则表达式是...

    Perl中的文件读写学习笔记

    文件的读取和写入是Perl文件操作的核心部分。对于读取,有几种方式: 1. 读取单行:`$line = ;` 2. 一次性读取整个文件内容到数组:`@array = ;` 写入文件通常涉及`print`函数: ```perl open (OUTFILE, "&gt;...

    perl - 基础

    5. **文件操作**:Perl可以轻松地读写文件,包括打开、关闭、读取、写入和追加操作。 6. **模块**:Perl拥有丰富的CPAN(Comprehensive Perl Archive Network)库,包含数千个预编译的模块,可直接用于各种功能的...

Global site tag (gtag.js) - Google Analytics