3

perl でテキスト ファイルを処理しようとしています。ファイルのデータをデータベースに保存する必要があります。私が抱えている問題は、いくつかのフィールドに改行が含まれていることです。これらのフィールドを含める最良の方法は何ですか?

data.txt ファイルの例:

ID|Title|Description|Date
1|Example 1|Example Description|10/11/2011
2|Example 2|A long example description
Which contains
a bunch of newlines|10/12/2011
3|Example 3|Short description|10/13/2011

現在の (壊れた) Perl スクリプト (例):

#!/usr/bin/perl -w
use strict;

open (MYFILE, 'data.txt');
while (<MYFILE>) {
    chomp;
    my ($id, $title, $description, $date) = split(/\|/);

    if ($id ne 'ID') {
        # processing certain fields (...)

        # insert into the database (example)
        $sqlInsert->execute($id, $title, $description, $date);
    }
}
close (MYFILE);

例からわかるように、ID 2 の場合、未定義の変数を参照しようとするとエラーが発生するいくつかの行に分割されます。それらをどのように正しいフィールドにグループ化しますか?

前もって感謝します!(質問が十分に明確で、タイトルを定義するのが難しいことを願っています)

4

3 に答える 3

5

行を分割する前に、セパレーターの数を数えるだけです。足りない場合は、次の行を読んで追加してください。tr演算子は、文字を数える効率的な方法です。

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

open (MYFILE, '<', 'data.txt');
while (<MYFILE>) {
    # Continue reading while line incomplete:
    while (tr/|// < 3) {
        my $next = <MYFILE>;
        die "Incomplete line at end" unless defined $next;
        $_ .= $next;
    }

    # Remaining code unchanged:
    chomp;
    my ($id, $title, $description, $date) = split(/\|/);

    if ($id ne 'ID') {
        # processing certain fields (...)

        # insert into the database (example)
        $sqlInsert->execute($id, $title, $description, $date);
    }
}
close (MYFILE);
于 2011-05-20T17:29:14.790 に答える
0

フィールドの数が必要になるまで次の行を読みます。そのようなもの(私はそのコードをテストしていません):

my @fields = split(/\|/);
unless ($#fields == 3) { # Repeat untill we get 4 fields in array

  <MYFILE>; # Read next line      
  chomp;

  # Split line
  my @add_fields = split(/\|/); 

  # Concatenate last element of first line with first element of the current line
  $fields[$#fields] = $fields[$#fields] . $add_fields[0]; 

  # Concatenate remaining array part
  push(@fields, @add_fields[1,$#add_fields]);

}
于 2011-05-20T17:19:33.590 に答える
0

すべての行/レコードの最後の文字としてパイプ区切り文字を含めるように data.txt ファイルを変更できる場合、ファイル全体を丸呑みして、生のフィールドに直接分割することができます。このコードは、あなたが望むことをします:

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

my @fields;
{
  $/ = "|";
  open (MYFILE, 'C:/data.txt') or die "$!";
  @fields = <MYFILE>;
  close (MYFILE);

  for(my $i = 0; $i < scalar(@fields); $i = $i + 4) {
    my $id = $fields[$i];
    my $title = $fields[$i+1];
    my $description = $fields[$i+2];
    my $date = $fields[$i+3];
    if ($id =~ m/^\d+$/) {
        # processing certain fields (...)

        # insert into the database (example)
    }
  }
}
于 2011-05-20T18:04:44.320 に答える