perl - 如何在 perl 中解析多行、固定宽度的文件?

标签 perl parsing fixed-width

我有一个文件需要按以下格式解析。 (所有分隔符都是空格):

field name 1:            Multiple word value.
field name 2:            Multiple word value along
                         with multiple lines.
field name 3:            Another multiple word
                         and multiple line value.

我熟悉如何解析单行固定宽度文件,但对如何处理多行感到困惑。

最佳答案

#!/usr/bin/env perl

use strict; use warnings;

my (%fields, $current_field);

while (my $line = <DATA>) {
    next unless $line =~ /\S/;

    if ($line =~ /^ \s+ ( \S .+ )/x) {
        if (defined $current_field) {
            $fields{ $current_field} .= $1;
        }
    }
    elsif ($line =~ /^(.+?) : \s+ (.+) \s+/x ) {
        $current_field = $1;
        $fields{ $current_field } = $2;
    }
}

use Data::Dumper;
print Dumper \%fields;

__DATA__
field name 1:            Multiple word value.
field name 2:            Multiple word value along
                         with multiple lines.
field name 3:            Another multiple word
                         and multiple line value.

关于perl - 如何在 perl 中解析多行、固定宽度的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8510445/

相关文章:

perl - 将哈希排序为数组中的键

python - 解析关键字并在数组中查找相关行

r - 在不使用 for 循环的情况下将字符串解析为 n-gram - R

PHP:循环并解析数组

Python 使用 Pandas 读取固定宽度文件,无需任何数据类型解释

powershell - 用于批量查找和替换特定文本的脚本,然后在 .txt 文件中的替换文本后添加 3 个空格

perl - 为什么 find_child_elements 忽略 Perl Selenium 中的第一个参数?

perl - 验证失败 : Must issue a STARTTLS command first

perl - Perl 面向对象设计模式

CSS - 固定宽度和居中定位 div 之间的流体 div