#!/usr/bin/perl use strict; use warnings; my %devices; # a HOH Hash of Hash {name}{device} my $current_name; while ( my $line = ) { $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