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 Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Array or Hash ?

Status
Not open for further replies.

Extension

Programmer
Joined
Nov 3, 2004
Messages
311
Location
CA
Hi,

I'm currently building a little relationship between two files. I've converted them into arrays and looped around them to come up the output needed.
Now, this would be better handled with a hash, so I would like to get your expertise on the subject.

Here's my current code and data. How to easily convert this to an hash.


Code:
[i]group.txt[/i]
ID|NUMBER|NAME|ALTENATE_NAME|RANK
A|G1|Grp1|Group 1|2
B|G2|Grp2|Group 2|1
C|G3|Grp3|Group 3|3
D|G4|Grp4|Group 4|4

Code:
[i]ind.txt[/i]
ID|GROUP|NAME|ALTENATE_NAME
334223|A|PG|Peter Gibbons
235997|A|MB|Michael Bolton
448977|C|SN|Samir Nagheenanajar
34545|C|MW|Milton Waddams
34545|A|BL|Bill Lumbergh
309933|D|BS|Bob Slydell

Code:
	# Open Group File
	open(GROUP,"group.txt") || die("Error !");					
	my $FieldNames = <GROUP>;	
	@Groups = map {chomp; [split /\|/, $_]} <GROUP>;
	close(GROUP);
	
	# Open Ind File
	open(IND,"ind.txt") || die("Error !");					
	my $FieldNames = <IND>;	
	@Individuals = map {chomp; [split /\|/, $_]} <IND>;
	close(IND);
	
	foreach my $Group (sort { $a->[4] cmp $b->[4] } @Groups) {
		
		print qq! - [$Group->[2]] $Group->[3] \n!;
		
		foreach my $Ind (sort { $a->[3] cmp $b->[3] } @Individuals) {
			
			if ($Ind->[1] eq $Group->[0]) {
				print qq! \t [$Ind->[2]] $Ind->[3]  \n!;
			}
	
		}
		
	}


Current output; I don't want to display Groups which doesn't have any Individuals under it, in this example Grp2.
Code:
 - Grp2
 - Grp1 
 	 [BL] Bill Lumbergh  
 	 [MB] Michael Bolton  
 	 [PG] Peter Gibbons  
 - Grp3 
 	 [MW] Milton Waddams  
 	 [SN] Samir Nagheenanajar  
 - Grp4 
 	 [BS] Bob Slydell

Thank you.
 
In retrospect, this feels like I'm doing home work. Shrug, oh well. It's early, and the code is probably full of bugs anyway. Enjoy:

Code:
open(GROUP,"group.txt") || die("Error !");
my $FieldNames = <GROUP>;
@Groups = map {chomp; [split /\|/, $_]} <GROUP>;
close(GROUP);

# Open Ind File
open(IND,"ind.txt") || die("Error !");
my $FieldNames = <IND>;
@Individuals = map {chomp; [split /\|/, $_]} <IND>;
close(IND);

[COLOR=green]my %groups = map {$_->[0] => $_} @Groups;

my $lastGroup = '';
foreach my $Ind (sort {$groups{$a->[1]}[4] cmp $groups{$b->[1]}[4] ||
					   $a->[3] cmp $b->[3]} @Individuals)
{
	if ($lastGroup ne $Ind->[1]) {
		my $Group = $groups{$Ind->[1]};
		print qq! - [$Group->[2]] $Group->[3] \n!;
		$lastGroup = $Ind->[1];
	}
		
	print qq! \t [$Ind->[2]] $Ind->[3]  \n!;
}[/color]
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top