0

我需要使用外部数据,一个纯文本文件,其中包含要在 Perl 中处理的数据(我正在学习这种语言)。

{NAME}
orga:21:12348:oragnisation
serv:22:12348:service
{NAME-END}
{DATA}
palm:data:fluid:147
rose:data:fluid:149
{DATA-END}
{OTHER}
palm:data:fluid:147
rose:data:fluid:149
germ:data:fluid:189
{OTHER-END}

我如何读取这个文件并将每个部分存储在数组中(部分是已知的并在{xxxx}和之间分隔{xxxx-END}。部分中的每个数据都转换为一个列表并存储在数组中。我希望有这样的东西,例如:

@name = ( ("orga","21","12348","organisation"), ("serv","22","12348","service") )
4

2 回答 2

6

尝试创建根据其他变量的值命名的变量是一个坏主意。最好的方法是构建数组的散列,而不是像@name.

像这个程序这样的东西会做你需要的。我曾经用来Data::Dump显示程序构建的数据结构。

use strict;
use warnings;

use Data::Dump;

open my $fh, '<', 'data.txt' or die $!;

my %data;
my $sect;
while (<$fh>) {
  chomp;
  if (/^\{(\w+)\}$/) {
    $sect = $1;
  }
  elsif (/^\{($sect-END)\}$/) {
    undef $sect
  }
  elsif (defined $sect) {
    push @{ $data{$sect} }, [split /:/];
  }
}

dd \%data;

输出

{
  DATA  => [
             ["palm", "data", "fluid", 147],
             ["rose", "data", "fluid", 149],
           ],
  NAME  => [
             ["orga", 21, 12348, "oragnisation"],
             ["serv", 22, 12348, "service"],
           ],
  OTHER => [
             ["palm", "data", "fluid", 147],
             ["rose", "data", "fluid", 149],
             ["germ", "data", "fluid", 189],
           ],
}
于 2013-01-08T10:57:29.420 回答
0

像这样的东西怎么样:

my %list;
while(<DATA>) {
    chomp;
    if (/^\{(.*?)\}/ .. /^\{${1}-END\}/) {
        push @{$list{$1}}, $_ unless /^\{/;
    }
}
say Dumper\%list;

输出:

$VAR1 = {
          'OTHER' => [
                     'palm:data:fluid:147',
                     'rose:data:fluid:149',
                     'germ:data:fluid:189'
                   ],
          'NAME' => [
                    'orga:21:12348:oragnisation',
                    'serv:22:12348:service'
                  ],
          'DATA' => [
                    'palm:data:fluid:147',
                    'rose:data:fluid:149'
                  ]
        };
于 2013-01-08T10:53:27.473 回答