Here's one way: If there is a character that you know doesn't occur in either the name or the date (like a tab), you can use that to separate the two and make a single hash key out of it. Note that in the sample data that you've posted here, you don't have any tabs, so I've had to guess that all of your columns are separated by tabs. However, in that case, my ( $name, $rest ) = split /\t/; is only grabbing the first two columns. Also, you probably want to chomp your lines.
use strict; use warnings; my %res; while (<DATA>) { chomp; my ( $name, $date, @rest ) = split /\t/; push @{ $res{"$name\t$date"} }, @rest; } for my $key ( sort keys %res ) { my ( $name, $date ) = split /\t/, $key, 2; print "$name,$date:", join( "|", @{ $res{$key} } ), "\n"; } __DATA__ nick 20/5/1950 one john 18/2/1980 two two and a half nick 19/6/1978 three nick 20/5/1950 four nick 12/9/2000 five john 15/6/1997 six nick 20/5/1950 seven eight
Output:
john,15/6/1997:six john,18/2/1980:two|two and a half nick,12/9/2000:five nick,19/6/1978:three nick,20/5/1950:one|four|seven|eight
In the above code, using \t to separate the hash key is safe, because of the split /\t/ I know that none of the strings will contain tabs. If you choose a separator character of which you're not sure if it's contained in the strings, like say |, you may want to add a check like die $name if $name=~/\|/; die $date if $date=~/\|/; to play it safe. Also, you can use a separator that is very unlikely to appear, like $/ or \0 (but again, if you want to code defensively, check for its presence anyway). (Update: $/ is the input record separator, which chomp removes for you. Also made minor fix to the latter two regexes.)
Update 2: I should also mention that using a module like Text::CSV is generally better for reading this kind of data, because it handles things like quoted fields and escaped characters for you (also install Text::CSV_XS for speed).
In reply to Re: which data structure do I need for this grouping problem?
by haukex
in thread which data structure do I need for this grouping problem?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |