lurgann
lurgann

Reputation: 23

parse file and store delimited section in array in Perl

I need to work with external data, a plain text file with data to process in Perl (I'm learning this language).

{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}

How can I read this file and store each section in array (section are known and delimited between {xxxx} and {xxxx-END}. Each data in section is transformed into is a list and store in array. I wish to have something like this, for example:

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

Upvotes: 0

Views: 504

Answers (2)

Borodin
Borodin

Reputation: 126742

It is a bad idea to try to create variables named according to the value of other variables. The best way is to build a hash of arrays rather than separate named arrays like @name.

Something like this program will do what you need. I have used Data::Dump to display the data structure that the program has built.

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;

output

{
  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],
           ],
}

Upvotes: 6

Toto
Toto

Reputation: 91498

How about something like this:

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

output:

$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'
                  ]
        };

Upvotes: 0

Related Questions