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

Sorting associative array elements and writing them to a file

Status
Not open for further replies.

djnsh

Programmer
Aug 1, 2003
4
GB
I have set up an associative array to store the contents of two different sets of files so that I can eventually sort the contents depending upon a common factor. When I output to the screen using the following lines of code:

print ($hits{'values'}, "\n");
print ($hits{'files'}, "\n" );

this gives the output:
...
ABS.45354
23442

ABS.45354
23875

ABS.45353
245764

ABT.3133
198

ABT.3133
223 ... and so on for all files in a directoy.

Note that the ABS.45353 is the filename which is the common factor. However my problem is how to output to a file every array element associated with ABS.45353 so that I end up with a sorted file containing a list of the numbers associated with each corresponding file:
e.g: files ABS.45353 containing:
23442
23875
245674

e.g: file ABT.3133 containing:
198
223

Any help is appreciated.
 
OK, assuming we have an input file containing data in the following format:

ABS.45354 23442
ABS.45354 23875
ABS.45353 245764
ABT.3133 198
ABT.3133 223
ABS.45358 23442
ABS.45358 23875
ABS.45358 245764
ABT.3132 198
ABT.3132 223

This script does what you require:

#!/usr/contrib/bin/perl
my $input = $ARGV[0]; # read data file
########################################
#read data file into hash
my %hits;
my ($i, $files, $values);
open (FILE1, "$input");
while (<FILE1>) {
next if /^\s+$/;
chomp;
my ($file, $value) = split(/\s+/);
$hits{$i}= {
files => $file,
values => $value
};
$i++;
}
########################################
#write just the filenames into %seen
%seen = ();
foreach $keys(keys %hits) {
$seen{$hits{$keys}{files}}++;
}
#remove duplicate entries and sort remaining list
@uniq = keys %seen;
@uniq=sort(@uniq);
foreach $file(@uniq) {
print &quot;file = $file\n&quot;;
}
########################################
# main comparison section
foreach $entry(@uniq) {
open (FILE, &quot;>$entry&quot;) or die &quot;cannot create $entry: $!&quot;; #create file
foreach $key(keys %hits) {
if ($entry eq $hits{$key}{files}) {
print FILE &quot;$hits{$key}{values}\n&quot;; #write value to file
}
}
close (FILE); #close file
}

Hope this helps.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top