06.Perl -- 文件操作

2022-05-20  本文已影响0人  QXPLUS

Perl 句柄

句柄的定义

输入输出句柄

间接文件句柄

STDIN

print "please input the data\n";  # 提示用户输入数据
my $data = <STDIN>;                  # 用户从外部(键盘)输入数据:ABC(回车)
print "The data is $data\n";        # 打印出用户输入的数据:The data is ABC

STDOUT

print "Here is the example\n"
# Here is the example
print STDOUT "Here is the example\n"
# Here is the example

STDERR

自定义句柄

打开文件

使用open函数打开文件

if (open (MYFILE, "mydatafile.txt"))
{
    print "we open the file successfully\n";
}
else
{
    print "Cannot open the file\n";
    exit 1;
}

die函数

print "script start!\n";
open (MYFILE, "mydatafile.txt") || die "This file not exists";
open (MYFILE, "test.txt") || die "Cannot open 
myfile: $!\n";
# Cannot open myfile: No such file or directiry
use strict;
# 打开`*.fq.gz` 或者`*.fq`文件
my ($read1, $read2) = @ARGV;

if ($read1 =~ /\.gz$/) {
    open(R1, "gzip -dc $read1|") || die $!;
}
else {
    open(R1, "$read1") || die $!;
}

if ($read2 =~ /\.gz$/) {
    open(R2, "gzip -dc $read1|") || die $!;
}
else {
    open(R2, "$read1") || die $!;
}

warn函数

if (!open(MYFILE, "output.txt"))
{
    warn "Cannot read output: \n $!";
}
else
{
    print "start to read output file";
}

print "here is another command\n";

# Cannot read output: 
# No such file or directory at C:\Perl\File
# here is another command

读写文件

读取文件

open (FILE, "finename") || die "Cnnot open the file";
$line = <FILE>;       # 读取文件
close FILE;                # 关闭文件句柄

说明:

open (FILE, "myfile.txt") || die "Cnnot open the file: $!\n";
while ($a = <FILE>)
{
    print $a;                # 每次打印文件的一行内容,直到读取完毕。
}
close FILE;                # 关闭文件句柄
open (FILE, "myfile.txt") || die "Cnnot open the file: $!\n";
my @arr = <FILE>;
print @arr;                # 打印文件的全部内容
close FILE;                # 关闭文件句柄

写入文件

open (MYFILE, ">mydatafile.txt");  # 定义以覆盖的方式写入
print MYFILE "abc";   # 写入字符串abc到文件mydatafile.txt
close MYFILE;

关闭文件句柄

每次打开句柄后,都要记得关闭

文件测试运算符

测试文件的必要性

文件测试运算符

-r read 例如,-r 'file': 可以读取'file'文件,则返回为真
-w write 例如,-w $a$a中包含的文件名是可以写入的文件,则返回为真
-e exist 例如, -e 'myfile': 'myfile'文件存在,则返回为真
-z zero 例如, -z 'data': 'data'文件存在,但是文件为空,则返回为真
-s size 例如, -s 'data': 'data'文件存在,则返回'data'的大小(字符个数)

-f file 例如,-f 'novel.txt':'novel.txt'是个普通文件(区别于二进制文件、可执行文件等),则为真
-d directory 例如,-d '/tmp': '/tmp'是个目录,则为真

-T text 例如,-T 'unkonw':'unkonw'为文本文件,则为真
-B bin 例如,-B 'unkonw':'unkonw'为二进制文件,则为真
-M 例如,-M 'foo': 返回'foo'文件被修改后经过的时间

上一篇 下一篇

猜你喜欢

热点阅读