如何使用Perl更新一组原始文件?

时间:2011-04-01 14:59:07

标签: perl

我想获取原始文件的数组并更新它们。这意味着我想使用output_files作为更新的input_files

例如:

  

a_all.txt ---更新到---> a2_all.txt ---更新到 - > a3_all.txt ---更新到 - a3_all.txt
  接下来在阵列中   b_all.txt ---更新到---> b2_all.txt ---更新到 - > b3_all.txt ---更新到 - b3_all.txt
  etc..to z_all.txt

这是我到目前为止开始的代码,但我不知道如何完成它..

#!/usr/bin/perl

use warnings;
use strict;

my $_arry_counter = 1;

my @input_files_1 = qw(a b c d e f g h i j k l m n o p q r s t u v w x y z);

foreach my $file_names (@input_files${_array_counter}) {   
    print  open 'INPUT_FILES','<',"/home/${file_names}_all.txt" or die "unable to open file !";

    while(<INPUT_FILES>) {
         open 'INPUT_FILES','>>',"/home/$file_count\
    }

    my @input_files_\$_ = open 'INPUT_FILES',>>
}

1 个答案:

答案 0 :(得分:1)

这是一个更好的主意:

#!/usr/bin/perl

use warnings;
use strict;
use File::Slurp qw<append_file read_file>;

my @input_files = ( 'a'..'z' );

foreach my $file_name ( @input_files ) {   
    my $contents = read_file( "/home/${file_name}_all.txt" );
    append_file( "/home/${file_name}${_}_all.txt", $contents ) foreach 2..3;
}

我不认为您对正在写出的内容进行了更改,因此您只是想将${letter}_all.txt转储到${letter}${num}_all.txt

或者如果你想知道如何做一个更理智的标准perl版本,我做了以下更改。

use warnings;
use strict;
use English qw<$OS_ERROR>;

my $_arry_counter = 1;
# no reason to write the whole alphabet
my @input_files_1 = 'a'..'z';

# I'm not sure what you thought you could do with your foreach loop expression.
foreach my $file_names (@input_files_1) { 
    # save! the path
    my $path = "/home/${file_names}_all.txt";
    # open *lexical* handles and die with *explicit* message and OS error.
    open my $input,'<', $path or die "unable to open file '$path'! - $OS_ERROR";

    # best way to do this to minimze IO is to write two files at once to two
    # two different handles.
    my @outs 
        = map { 
            # repeating practice with inputs
            my $out_path = "/home/${file_names}$_\_all.txt";
            open my $out, '>>',  or die  "unable to open file '$out_path'! - $OS_ERROR";
            $out;
        } 2..3;
    while ( my $line = <$input> ) { 
        # in this foreach $_ is a handle, so we need to save the line in a var.
        print $_ $line foreach @outs;
    }
    # close each output
    close $_ foreach @outs;
    # close current input
    close $input;
}

我在评论中添加的内容更像是这样:

use English qw<$RS>; # record separator -> $/

my $regex = qr{
        (^ \@ .* )
        # note that I turn on s for *select* sections
        ( (?s) .*? )
        ( ^ (windows|linux) .* )
        ( (?s) .*? )
        ( ^ (windows|linux) .* )
        ( (?s) .*? )
    }mx;
foreach my $file_name ( @input_files ) { 
    my $contents = read_file( "/home/jbutler/final/${file_name}_all.txt" ); 
    local $RS = 'Data';
    $contents =~ s/$regex/$1$2­$3$4\n__Data__\n$1\n$5$6/m; 
    append_file( "/home/jbutler/final/${file_name}${_}_all.txt", $contents ) foreach 2..3; 
} 

但我没有测试过这个。