如何在Perl中从文件读取的单个字段中处理/存储多行? [英] How do I handle/store multiple lines into a single field read from a file in perl?

查看:144
本文介绍了如何在Perl中从文件读取的单个字段中处理/存储多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在perl中处理文本文件.我需要将文件中的数据存储到数据库中. 我遇到的问题是某些字段包含换行符,这使我有些不满意. 包含这些字段的最佳方法是什么?

I am trying to process a text file in perl. I need to store the data from the file into a database. The problem that I'm having is that some fields contain a newline, which throws me off a bit. What would be the best way to contain these fields?

示例data.txt文件:

Example data.txt file:

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脚本(示例):

The current (broken) Perl script (example):

#!/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的情况下,它分成几行,在尝试引用那些未定义的变量时会导致错误.您如何将它们分组到正确的字段?

As you can see from the example, in the case of ID 2, it's broken into several lines causing errors when attempting to reference those undefined variables. How would you group them into the correct field?

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

Thanks in advance! (I hope the question was clear enough, difficult to define the title)

推荐答案

在分割线之前,我只计算分隔符的数量.如果您没有足够的内容,请阅读下一行并追加. 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);

这篇关于如何在Perl中从文件读取的单个字段中处理/存储多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆