http://qs321.pair.com?node_id=11123134


in reply to Applying regex to each line in a record.

This approach is very generalized (some might say over-generalized :) and more verbose, but has the advantage that it is very flexible and can be highly specialized. E.g., patterns for top level key and lower level key/values can be individually specified. The script does a fair amount of data validation. I'm using a slightly different example dataset for testing.

Script extract_HoH_1.pl:

use strict; use warnings; use autodie; use Data::Dumper; my $filename = '11123126_1.dat'; # could take this from command line # ignore blank or # comment lines use constant IGNORE => qr{ ^ \s* (?: [#] .* )? $ }xms; my $rx_identifier = qr{ \w+ }xms; my $rx_toplevel = qr{ $rx_identifier }xms; my $rx_key = qr{ $rx_identifier }xms; my $rx_value = qr{ $rx_identifier }xms; my $toplevel; my %hash; open my $fh, '<', $filename; RECORD: while (my $record = <$fh>) { next RECORD if $record =~ IGNORE; # print Dumper $record; # for debug my $got_toplevel = my ($tl) = $record =~ m{ ^ \s* ($rx_toplevel) \s* : \s* $ }xms; $toplevel = $tl, next RECORD if $got_toplevel; # print Dumper $toplevel; # for debug my $got_key_val = my ($key, $value) = $record =~ m{ ^ \s* ($rx_key) \s* : \s* ($rx_value) \s* $ }xms; # print Dumper $key, $value; # for debug die "no top level seen" unless defined $toplevel; $hash{$toplevel}{$key} = $value, next RECORD if $got_key_val; # no valid record seen. die "bad record '$record'"; } # end while RECORD print Dumper \%hash; close $fh; exit; # subroutines ###################################################### # none for now

Example dataset 11123126_1.dat:

first: this:that here:there when:what firstAsValue:first how:where now:later first:firstAsKey second: this2:that2 secondAsValue:second here2:there2 second:secondAsKey when2:what2 how2:where2 now2:later2

Example run:

Win8 Strawberry 5.8.9.5 (32) Sat 10/24/2020 15:46:02 C:\@Work\Perl\monks\pritesh_ugrankar >perl extract_HoH_1.pl $VAR1 = { 'first' => { 'when' => 'what', 'here' => 'there', 'first' => 'firstAsKey', 'now' => 'later', 'how' => 'where', 'firstAsValue' => 'first', 'this' => 'that' }, 'second' => { 'now2' => 'later2', 'here2' => 'there2', 'how2' => 'where2', 'when2' => 'what2', 'secondAsValue' => 'second', 'this2' => 'that2', 'second' => 'secondAsKey' } };


Give a man a fish:  <%-{-{-{-<