【问题标题】:Perl copying specific lines of VECT FilePerl 复制 VECT 文件的特定行
【发布时间】:2018-11-24 18:01:12
【问题描述】:

我想复制文件的第 7-12 行,例如 this example .vect file, 进入同一目录中的另一个 .vect 文件。

我希望将每一行复制两次,并将每行的两个副本连续粘贴到新文件中。

这是我目前使用的代码,希望继续在 Perl 中使用这些方法/包。

use strict;
use warnings;
use feature qw(say);

# This method works for reading a single file
my $dir = "D:\\Downloads";

my $readfile  = $dir ."\\2290-00002.vect";
my $writefile = $dir . "\\file2.vect";

#open a file to read
open(DATA1, "<". $readfile) or die "Can't open '$readfile': $!";;

# Open a file to write
open(DATA2, ">" . $writefile) or die "Can't open '$writefile': $!";;

# Copy data from one file to another.
while ( <DATA1> ) {
    print DATA2 $_;
}

close( DATA1 );
close( DATA2 );

使用我在上面使用的相同打开和关闭文件语法来执行此操作的简单方法是什么?

【问题讨论】:

    标签: perl file file-io scripting vector-graphics


    【解决方案1】:

    只需将print这一行修改为

    print DATA2 $_, $_ if 7 .. 12;
    

    详情请见Range Operators in "perlop - Perl operators and precedence"

    【讨论】:

    • 太棒了!非常感谢!这将有很大帮助!
    【解决方案2】:

    值得记住 Tie::File 将文件逐行映射到 Perl 数组的模块,并允许您使用简单的数组操作来操作文本文件。处理大量数据时可能会很慢,但对于大多数涉及常规文本文件的应用程序来说,它是理想的

    将一系列行从一个文件复制到另一个文件变成了复制数组切片的简单问题。请记住,文件从数组元素 0 中的第一行开始,因此第 7 到 12 行位于索引 6...11

    这是执行您所要求的 Perl 代码

    use strict;
    use warnings;
    
    use Tie::File;
    
    chdir 'D:\Downloads' or die $!;
    
    tie my @infile,  'Tie::File', '2290-00002.vect' or die $!;
    tie my @outfile, 'Tie::File', 'file2.vect' or die $!;
    
    @outfile = map { $_, $_ } @infile[6..11];
    

    没有其他要求。是不是很整洁?

    【讨论】:

      猜你喜欢
      • 2014-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2011-07-20
      相关资源
      最近更新 更多