I saw your question about accounting for Brian having more than one of the same device. Here is yet another solution... I didn't use a HoH in my first solution partly because that can be a difficult concept for beginners.
In general I don't recommend approaches that require reading the entire input file into memory and then parsing that memory copy of the file because that often essentially means that the data is being "handled" in some way more than once and can take a lot of memory in the process. Some of the files that I work with can get quite large.
#!/usr/bin/perl
use strict;
use warnings;
my %devices; # a HOH Hash of Hash {name}{device}
my $current_name;
while ( my $line = <DATA>)
{
$current_name = $1 if ($line =~ m/^name\s+(\w+)\s+/);
if ( (my $device) = $line =~ /^device\s+([\w\s]+)\n/)
{
$device =~ s/[ ]+/ /g; # multiple-space to a single space
$devices{$current_name}{$device}++;
}
}
# print the %devices hash - requires 2 loops
foreach my $name (sort keys %devices)
{
print "$name:\n";
foreach my $device (keys %{$devices{$name}})
{
print " $devices{$name}{$device}\t$device\n";
}
}
=Prints
Andrew:
1 ipad 2009
Brian:
3 ipad 2001
ryan:
1 ipad 2005
1 cell 2009
=cut
__DATA__
socks something
name Brian
shirt yellow
socks black
device ipad 2001
device ipad 2001
device ipad 2001
tag no
tag 0
name Andrew
shirt orange
socks black
device ipad 2009
tag no
tag 0
name ryan
shirt blue
socks black
device ipad 2005
device cell 2009
tag yes
tag 1
-
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.
|