如何在perl中从文件读取的单个字段中处理/存储多行?

Hig*_*ife 3 perl file-io split chomp

我正在尝试在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
Run Code Online (Sandbox Code Playgroud)

当前(损坏的)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);
Run Code Online (Sandbox Code Playgroud)

从示例中可以看出,在ID 2的情况下,它会分成几行,在尝试引用这些未定义的变量时会导致错误.你会如何将他们分组到正确的领域?

提前致谢!(我希望问题很清楚,很难定义标题)

cjm*_*cjm 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);
Run Code Online (Sandbox Code Playgroud)