You're reading your data twice: once into $text and again with a regex. I assume your data is in a file and you've only shown a small portion of it.

Now that you've shown the data structure you're trying to create (in "Re^2: Parse structured text using regex"), I'd probably parse it line-by-line.

#!/usr/bin/env perl use strict; use warnings; my $parsed = parse(\*DATA); use Data::Dump; dd $parsed; sub parse { my ($fh) = @_; my ($parsed, $car_key, $model_key); my $last_record_only_has_key = 0; my $new_model_array = 1; while (<$fh>) { my ($leader, $info) = /^([A-Z]*)[|]?(\S*)\s*$/; if ($leader) { if (! $info) { $car_key = $model_key if $last_record_only_has_key; $car_key = $leader unless $car_key; $last_record_only_has_key = 1; } $model_key = $leader; $new_model_array = 1; next unless $info; } $last_record_only_has_key = 0; for (split /[|]/ =>$info) { my ($key, $value) = split /=/; if ($new_model_array) { push @{$parsed->{$car_key}}, {$model_key => { $key => +$value }}; $new_model_array = 0; } else { $parsed->{$car_key}[-1]{$model_key}{$key} = $value; } } } return $parsed; } __DATA__ CAR MODEL|name=Mustang|Quality=A|Speed= MODEL|Chevy=Cavalier|MPG=20 MODEL |Color=blue|type=hatchback|crashrating=spectacular |explodes=true|speed=|storage=none,little

Output:

{ CAR => [ { MODEL => { name => "Mustang", Quality => "A", Speed => "" + } }, { MODEL => { Chevy => "Cavalier", MPG => 20 } }, { MODEL => { Color => "blue", crashrating => "spectacular", explodes => "true", speed => "", storage => "none,little", type => "hatchback", }, }, ], }

-- Ken


In reply to Re: Parse structured text using regex by kcott
in thread Parse structured text using regex by trippledubs

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.