For starters, ALWAYS 'use strict;' and 'use warnings;' at the beginning
of your scripts. It's a little annoying at first, but it saves you from
some very time-consuming mistakes down the line.
Okay, here is one way to do the kind of thing I think you are asking to
do. Keep in mind that I took some liberties with style and naming, and
you may want to do it a bit differently if this doesn't make sense to
you.
##############################################################
use strict;
use warnings;
#Each key of %groups is a group,
#the value is an array of users
my %groups;
#Each key of %users is a user,
#the value is an array of groups
my %users;
#open the input file
open(USERFH,"<users.txt") || die "Could not read users.txt!\n";
#For each line...
while(my $line = <USERFH>){
chomp $line;
#First item is the user name, the rest are the groups
my($user,@groups) = split(/\s+/,$line);
#Create a key with the user name
#and add the groups as a value
$users{$user} = [EMAIL PROTECTED];
#For each group, create a key in %groups and add
#the user to the end of the list
foreach my $group(@groups){
push @{$groups{$group}},$user;
}
}
close USERFH;
#Print out a list of groups with members
print "GROUPS\n";
print "======\n\n";
foreach my $group(sort keys %groups){
print "$group:\n";
foreach my $user(sort @{$groups{$group}}){
print "\t$user\n";
}
}
print "\n\n";
#Print out a list of users with groups they belong to
print "USERS\n";
print "=====\n\n";
foreach my $user(sort keys %users){
print "$user:\n";
foreach my $group(sort @{$users{$user}}){
print "\t$group\n";
}
}
################################################################
-----Original Message-----
From: Robin Smith [mailto:[EMAIL PROTECTED]
Sent: Monday, August 23, 2004 6:04 PM
To: [EMAIL PROTECTED]
Subject: Need help to sort data
Hi,
I have a flat file data in the form of user and groups. The user always
come first follow by the groups. Now I need to arrange then by groups.
This is the code I have been working with. the groups are listing but
the users are not. I am still fairly new to perl so I need someone
with simple code? Can someone offer any assistance ?
my %group_to_users = ();
while (my $line = <USERFH>) {
chomp ($line);
my ($user, @user_groups) = split ('\s+', $line);
for my $group (@user_groups) {
push @group_to_users, $user ;
$group_to_users{$group} = [$user] ;
}
}
close (USERFH);
for my $group (sort keys %group_to_users) {
print $group . ":\n";
print $group_to_users{$group} . "\n";
}
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
<http://learn.perl.org/> <http://learn.perl.org/first-response>