且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-20 18:47:05

在分割线之前,我只计算分隔符的数量.如果您没有足够的内容,请阅读下一行并追加. tr运算符是一种有效的字符计数方法.

I would just count the number of separators before splitting the line. If you don't have enough, read the next line and append it. The tr operator is an efficient way to count characters.

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