如何使用perl的Tie::File 模块删除文件固定行

如何使用perl的Tie::File 模块删除文件固定行

使用perl的Tie::File 模块删除文件固定行, 为了说明简单代码中处理的是固定第二行开始的3行长度。下面给出perl代码:

#! /usr/bin/perluse v5.14;use Tie::File;if (@ARGV == 0) {say "请输入一个文件名 !!!";exit 1;}my $filePath = $ARGV[0];tie my @arry, 'Tie::File', $filePath;# 删除第二行开始的三行内容# 如果这里的索引值越界, 对文件内容没有影响splice @arry, 1, 3;

这里的处理主要利用了perl的Tie::File 模块把数组和文件绑定,然后就可以使用perl的splice函数操作数组,从而达到操作文件的目的。对于Tie::File 模块的用法,可以使用perldoc Tie::File 查询到详细说明:

Perl 模块 Tie::File应用举例

1 Tie::File

建立一个list和file的关系,对list的操作会反映到file上去。

use Tie::File;tie @array, 'Tie::File', filename or die ...;$array[13] = 'blah'; # line 13 of the file is now 'blah'print $array[42]; # display line 42 of the file$n_recs = @array; # how many records are in the file?$#array -= 2; # chop two records off the endfor (@array) { s/PERL/Perl/g; # Replace PERL with Perl everywhere in the file}# These are just like regular push, pop, unshift, shift, and splice# Except that they modify the file in the way you would expectpush @array, new recs...;my $r1 = pop @array;unshift @array, new recs...;my $r2 = shift @array;@old_recs = splice @array, 3, 7, new recs...;untie @array; # all finished

2 应用举例

use Tie::File;my @array;my $filename = "a.txt";tie(@array,'Tie::File',$filename) or die;print "$array[3]";print "$#array";$array[3] = "hello";$array[1] = "world";splice(@array, 1, 0, "insert into 0 and 1 line");delete $array[$#array];$#array -= 2;print pop @array;untie($array);

3 more help

perldoc Tie::File

对于splice函数可以使用 perldoc -f splice 查询文档:

Perl 函数 splice

splice ARRAY, OFFSET, LENGTH, LISTsplice ARRAY, OFFSET, LENGTHsplice ARRAY, OFFSETsplice ARRAY

这个函数从一个 ARRAY 中删除 OFFSET 和 LENGTH 指明的元素,并且,如果给出了LIST,则用 LIST 的元素替换它。如果 OFFSET 是负数,那幺该函数从数组的后面向前数,但如果该值会伸到数组开头的前面,那幺就会抛出一个例外。在列表环境中,splice 返回从该数组中删除的元素。在标量环境中,它返回最后删除的元素,而如果没有的话返回 undef。如果新元素的数量不等于旧元素的数量,那幺该数组根据需要伸缩,并且元素的位置根据衔接后的情况进行改变。如果省略了 LENGTH,那幺该函数从数组里删除从 OFFSET 开始的所有东西。如果省略了 OFFSET,那幺该数组在读取的时候清空。下面的等式成立(假设 $[ 为 0):

splice 函数还可以方便地用于切开传递给子过程的参数列表。比如,假设列表长度在列表之前传递:

sub list_eq { # 比较两个列表值 my @a = splice(@_, 0, shift); my @b = splice(@_, 0, shift); return 0 unless @a == @b; # 长度相同? while(@a) { return 0 if pop(@a) ne pop(@b); } return 1;}if (list_eq($len, @foo[1..$len], scalar(@bar), @bar)) { ... }

不过,拿数组引用来干这事更清晰一些。

Perl 文本文件的读写操作、文件的重命名和删除、多个文本文件的合并实现代码

如何使用perl的Tie::File 模块删除文件固定行