当前位置: 代码网 > it编程>网页制作>Perl > 如何使用perl的Tie::File 模块删除文件固定行

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

2024年05月15日 Perl 我要评论
使用perl的tie::file 模块删除文件固定行, 为了说明简单代码中处理的是固定第二行开始的3行长度。下面给出perl代码:#! /usr/bin/perluse v5.14;use tie::

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

#! /usr/bin/perl
use 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 end
for (@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 expect
push @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, list
splice array, offset, length
splice array, offset
splice 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 模块删除文件固定行的文章就介绍到这了,更多相关perl删除文件固定行内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com