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

data structures in perl... 1

Status
Not open for further replies.

huskers

Programmer
Jan 29, 2002
75
0
0
US
Hi,

I have data from table which i want to store in a data structure. The data is as follows:

ab, 2
ab, 3
ab, 4
cd, 10
cd, 23
cd, 15
cd, 16
ef, 5
ef, 6
ef, 11
ef, 12
ef, 51

I want it in a data structure as follows:
ab 2, 3, 4
cd 23, 15, 16
ef 5, 6, 11, 12, 51

I have to pass ab and 2,3,4(in array) as parameters to another program. Can you tell me how I can do it. Thanks
 
Please post the code you have so far.
 
Code:
#!/usr/bin/perl -w
use strict;
use diagnostics;
my %results = ();
while(<>) {
  chomp;
  s/\s+//g;
  my @fields = split /,/,$_,-1;
  push @{$results{shift @fields}}, @fields;
}
foreach my $key (sort keys %results) {
  print "$key ", join(", ", @{$results{$key}}), "\n";
}


Trojan.
 
Now I need to know what you need to pass the params to so that I can show you how to do that part too.

$key (will be the "ab" part).
$results{$key} (will be the array of values).



Trojan.
 
Thank you very much Trojan. I need to pass the params to another perl script which takes $key and $results{$key} as arguments.
 
Trojan, Can you explain this line a little,

push @{$results{shift @fields}}, @fields;
 
Calling the other code is simple.
Code:
system("other_perl_script.pl", join(" ", $key, @{$results{$key}}) );
You could, of course, use backticks instead of the system function if you prefer.

OK, now for an explanation:

The "push @{$results{shift @fields}}, @fields;" is a little clever since it does a few things at once.
firstly, the "shift @fields" removes the "ab" (for example) from the array of fields so that we can use it as a key and so that it does not appear in the list of data fields.
The "$results{}" simply accesses a hash (lookup) with the key we just considered.
The "@{...}" causes the hash element to be treated as an array (reference) and finally the @fields is the list of fields to be added to that array (after the "ab" first element has been removed).

Quite a lot of work for a single line of code!
:)

Trojan.
 
Trojan

system(list), so you can lose the join
Code:
system("other_perl_script.pl", $key, @{$results{$key}});
Have a star fo the rest of the code, though...
 
Sorry, it was meant to be a join with a comma since the suggestion was for only 2 params (although the comma space combination could have made things interesting!!!).


Trojan.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top