in reply to perl parsing
G'day cbtshare,
Here's the technique I might have used for this task:
#!/usr/bin/env perl use strict; use warnings; use autodie; use constant { IN_FILE => 'pm_1200636_text.txt', HEADER => 0, KEY => 1, VALUE => 2, }; my %parsed; { open my $fh, '<', IN_FILE; my $name; while (<$fh>) { my @fields = split; if ($fields[HEADER] eq 'name') { $name = $fields[KEY]; next; } if ($fields[HEADER] eq 'device') { push @{$parsed{$name}{$fields[KEY]}}, $fields[VALUE]; next; } } } # For testing only use Data::Dump; dd \%parsed;
This only reads a record at a time, so there should be no memory issues that might occur when slurping entire files. The only data that persists after the anonymous block is %parsed: process that as necessary. Also note that as $fh goes out of scope at the end of the anonymous block, Perl automatically closes this for you (there's no need for a close statement in this instance).
I used the same data as you posted (see the spoiler).
Output from a sample run:
{ Andrew => { ipad => [2009] }, Brian => { ipad => [2001, 2001, 2001] }, ryan => { cell => [2009], ipad => [2005] }, }
See also: "perldsc - Perl Data Structures Cookbook"; autodie; open; and, Data::Dump. Everything else is very straightforward and basic Perl, but feel free to ask if anything is unclear.
— Ken
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: perl parsing
by cbtshare (Monk) on Oct 05, 2017 at 19:27 UTC | |
by kcott (Archbishop) on Oct 05, 2017 at 22:32 UTC | |
by cbtshare (Monk) on Oct 06, 2017 at 01:57 UTC | |
by kcott (Archbishop) on Oct 06, 2017 at 05:35 UTC |