3

I have a large txt file made of thousand of articles and I am trying to split it into individual files - one for each of the articles that I'd like to save as article_1, article_2 etc.. Each articles begins by a line containing the word /DOCUMENTS/. I am totally new to perl and any insight would be so great ! (even advice on good doc websites). Thanks a lot. So far what I have tried look like:

#!/usr/bin/perl
use warnings;
use strict;

my $id = 0;
my $source = "2010_FTOL_GRbis.txt";
my $destination = "file$id.txt";

open IN, $source or die "can t read $source: $!\n";

while (<IN>)
  {
    {  
      open OUT, ">$destination" or die "can t write $destination: $!\n";
      if (/DOCUMENTS/)
       {
         close OUT ;
         $id++;
       }
    }
  }
close IN;
4

2 に答える 2

4

/DOCUMENTS/それ自体が行に表示されるとしましょう。したがって、それをレコード区切りにすることができます。

use English     qw<$RS>;
use File::Slurp qw<write_file>;
my $id     = 0;
my $source = "2010_FTOL_GRbis.txt";

{   local $RS = "\n/DOCUMENTS/\n";
    open my $in, $source or die "can t read $source: $!\n";
    while ( <$in> ) { 
        chomp; # removes the line "\n/DOCUMENTS/\n"
        write_file( 'file' . ( ++$id ) . '.txt', $_ );
    }
    # being scoped by the surrounding brackets (my "local block"),
    close $in;    # an explicit close is not necessary
}

ノート:

  • use Englishグローバル変数を宣言します$RS。その「厄介な名前」は$/. 見るperldoc perlvar
  • 行区切りは、デフォルトの レコード区切りです。つまり、ファイル読み取りの標準単位はrecordです。デフォルトでは、これは「行」のみです。
  • リンクされたドキュメントにあるように、$RS はリテラル文字列のみを受け取ります。というわけで、記事の区切りは'/DOCUMENTS/'一行でいいという考えで、 を指定しnewline + '/DOCUMENTS/' + newlineました。これが行のどこかで発生するパスの一部である場合、その特定の値はレコード セパレータとして機能しません。
于 2012-07-30T13:00:04.683 に答える
2

プログラミング Perlを読みましたか? 入門に最適の一冊です!

あなたが何をしようとしているのか理解できません。記事を含むテキストがあり、すべての記事を別々のファイルに取得したいとします。

use warnings;
use strict;
use autodie qw(:all);

my $id          = 0;
my $source      = "2010_FTOL_GRbis.txt";
my $destination = "file$id.txt";

open my $IN, '<', $source;
#open first file
open my $OUT, '>', $destination;

while (<$IN>) {
    chomp;    # kill \n at the end
    if ($_ eq '/DOCUMENTS/') {  # not sure, am i right here or what you looking for
        close OUT;
        $id++;
        $destination = "file$id.txt";
        open my $OUT, '>', $destination;
    } else {
        print {$OUT} $_, "\n";     # print into file with $id name (as you open above)
    }
}
close $IN;
于 2012-07-30T10:02:05.543 に答える