perl学习笔记08_文件目录操作

文件和目录操作

0. Handler和IO::File的比较

读写文件有两种方法: Handler和IO::File.
使用IO::File的好处是,可以把句柄当作参数,传给子例程。

use IO::File;

my $file = "io.file";

#write to the file
my $out = IO::File -> new(">$file") or die "Can't write to file $file: $!\n";
&write_file($out);
$out -> close();

#read the file
my $in = IO::File -> new("<$file") or die "Can't read file $file: $!\n";
&read_file($in);
$in -> close();

sub write_file{
    my $fh = shift;
    print $fh "Test data - line1\n";
    print $fh "Test data - line2\n";
}

sub read_file{
    my $fh = shift;
    print while(<$fh>);
}

1. 读文件

1.1 使用Handler

my $filename = "file.txt";

open(FIN, "<$filename") or die "Cannot read file $filename: $!\n";

while(my $line=<FIN>){
    print($line);
}

close(FIN);

1.2 使用IO::File

#read the file
my $in = IO::File -> new("<$file") or die "Can't read file $file: $!\n";
print while(<$in>);
$in -> close();

2. 写文件

2.1 使用Handler

my $filename = "file.txt";

open(FOUT, ">$filename") or die "Cannot write file $filename: $!\n";

print(FOUT, "123456\n");

close(FOUT);

2.2 使用IO::File

use IO::File;

my $file = "io.file";

#write to the file
my $out = IO::File -> new(">$file") or die "Can't write to file $file: $!\n";
print $out "Test data - line1\n";
print $out "Test data - line2\n";

$out -> close();

3. File handle重回开头或结尾

seek FH, 0, 0;  # 跳到文件头
seek FH, 0, 2;  # 跳到文件尾
if(eof(FH)) {   # 判断是否到达文件尾

}

3. 文件查找等

3.1 File::Find(查找)

use File::Find;

find(\&wanted, "/xxx/xxx/script");
sub wanted{
    $File::Find::prune = 1 if(/ex/);      # prune=1, 跳过该目录
    if(/\.pl$/){
        print "File: $_\n";               # $_, 文件名
        print "Dir : $File::Find::dir\n"; # $File::Find::dir,路径名
        print "Path: $File::Find::name\n";# $File::Find::name, 全名, 即路径名/文件名.
    }
}

3.2 File::Copy(复制)

use File::Copy ;
copy("file1", "file2");
move("file2","file3");
copy(\*STDIN, "file4"); #获取标准输入, 保存到file4中. 标准输入以Ctrl+D结束.

3.3 File::Basename(文件名操作)

use File::Basename;

my $full_name = "~/script/cell/scr/cell_split.pl";

my $base      = basename($full_name); # cell_split.pl
my $dir       = dirname($full_name); # ~/script/cell/scr

# 处理basename:
#   .pl作为文件的后缀截取下来,放到第三个返回值$extension中,
#   basename剩余部分放到第一个返回值$name中.
# 处理后变量内容如下:
#   $name      ->  cell_split
#   $dir       ->  ~/script/cell/scr/
#   $extention -> .pl
my ($name, $dir, $extension) = fileparse($full_name, '\.pl');

3.x 路径操作

# 得到当前路径名, 类似于unix pwd命令. 
# 如果所在的目录是link目录,则得到的link的源目录的路径.
use Cwd;
my $dir = cwd;

posted @ 2023-07-17 11:28  编程驴子  阅读(27)  评论(0编辑  收藏  举报