#!/usr/bin/perl use warnings; use strict; my %Invoices; my $last_name = ''; my %data; while(my $line = ) { chomp $line; # Split the fields into a hash. Depending on your # data, this might be better done with Text::xSV. @data{qw(orig inv name date time)} = ($line, split(/\s+/, $line)); next unless $data{name} eq 'Robb' or $data{name} eq 'Larry'; next if $last_name eq $data{name}; # If this field passes the tests, save a *copy* for later use. push @{$Invoices{$data{name}}}, {%data}; } continue { # Store the last name seen $last_name = $data{name}; } # For each (Larry Robb) foreach (keys %Invoices) { # Sort the invoices by date then time, in reverse order. $Invoices{$_} = [sort { $b->{date} cmp $a->{date} or $b->{time} <=> $a->{time} } @{$Invoices{$_}}]; # Print out the most recent invoice. print "Most recent for $_: $Invoices{$_}[0]{orig}\n"; } __DATA__ 1056128833340 Robb 2003-06-20 665 ** 1056128833340 t028348 2003-06-20 607 1055439973653 T012697 2003-07-22 962 1055439973653 t012697 2003-07-22 948 1055439973653 t806174 2003-07-15 792 1055439973653 T806174 2003-07-15 791 1055439973653 t021191 2003-07-08 786 1055439973653 Robb 2003-06-17 503 1055439973653 Larry 2003-06-16 815 ** 1055439973653 t021191 2003-06-12 646