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

标签 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

当前(损坏的)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 的情况下,它被分成几行,在尝试引用那些 undefined variable 时导致错误。您如何将它们分组到正确的字段中?

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

最佳答案

我会在拆分行之前计算分隔符的数量。如果你没有足够的,阅读下一行并附加它。 tr operator是一种有效的字符计数方法。

#!/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);

关于perl - 如何将多行处理/存储到从 perl 文件读取的单个字段中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6075327/

相关文章:

perl - Perl中的函数参数分隔符?

perl zip 目录为空

php - 获取从资源传递给 fopen 的模式?

java - 使用扫描仪读取城市名称

c++ - 使用 getline() 从文件中读取多行

java - 从文本文件中读取和拆分整数以加在一起?

perl - Perl 中的 'for' 和 'foreach' 有什么区别?

bash - perl 脚本结束时会发生什么?

java - 如何轻松解析这个字符串?

java - 为什么 .split ("\\") 会产生异常?