Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

comment on

( [id://3333]=superdoc: print w/replies, xml ) Need Help??

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


In reply to Re: perl parsing by kcott
in thread perl parsing by cbtshare

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



  • 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.
Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others romping around the Monastery: (3)
As of 2024-04-20 02:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found