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.
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.