Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Shaun E on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

data structure needed? 1

Status
Not open for further replies.

LinguaFranca

Technical User
Jan 4, 2005
18
NL
I have a tab separated 3 column text file with $file, $source and $target on each row.
1st: I need to identify all rows with identical $source;
2nd: I'll take the result of the 1st step and compare the $target. If different $target are used for $source, the output should give me all rows of that $source. Hope, I am clear enough.

Input
Code:
file1	cancel	abbrechen
file1	cancel	abbrechen
file2	cancel	annulieren
file2	cancel	abbrechen
file1	change	ändern
file3	delete	löschen
file4	delete	leeren
file1	view	ansicht
file4	view	ansicht
file3	view	ansicht
Desired output
Code:
file1	cancel	abbrechen
file1	cancel	abbrechen
file2	cancel	annulieren
file2	cancel	abbrechen
file3	delete	löschen
file4	delete	leeren
Could you give a hint how to program this? Is it wise to use data structures (array of arrays?)
 
This would probably be a lot easier with hashes rather than arrays. Does the order matter? It's a bit more difficult of the order does matter, but doable.
 
Actually, the rows are listed at random, so first I have to sort on column 2 (see "Input"). The order of output doesn't matter as long as I get all identical $source grouped together.
 
See how this works for you.
Code:
my %h;

while (<DATA>) {
    unless (/^\s*$/) {
        chomp;
        my ($file, $source, $target) = split;
        push @{$h{$source}->{$target}}, $_;
    }
}

foreach my $source (sort keys %h) {
    # Checks for multiple targets within a source
    if (keys %{$h{$source}} > 1) {
        foreach my $target (sort keys %{$h{$source}}) {
            map {print "$_\n"} sort @{$h{$source}->{$target}};
        }
    }
}

__DATA__
file1    cancel    abbrechen
file4    delete    leeren
file2    cancel    annulieren
file3    view    ansicht
file1    change    ändern
file3    delete    löschen
file1    cancel    abbrechen
file1    view    ansicht
file2    cancel    abbrechen
file4    view    ansicht
 
You did the job! Thank you very much. Also for the quick response.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top