> I don't want to duplicate code. However, system2 has
> two compilers and I need to read each compiler's
> password file and store that data in a hash. Now,
> will the compiler_data hash contain the data for both
> compilers password files? How can I keep them
> separate and don't duplicate code?
> %compilers = (
> system1 => "compiler_a",
> system2 => ["compiler_b", "compiler_c"],
> system3 => "compiler_d",
> );
For consistency, the list of compilers for each system should
be an arrayref, even if there's only one.
> foreach $compiler (@{$compilers{$system}}) (
This won't compile; should be: foreach $compiler (...) {
Note curly brace: ^^^
> $compiler_passwd = $compilers{$system} .
> "_passwd";
> open ($compiler, "< $compiler_passwd") or die
> "Can't open file $compiler_passwd: $!\n";
You're using the name of the compiler as a filehandle name. This
will work, but you run the risk of colliding with filehandles
used by other modules. A better bet is the FileHandle module;
see below.
> while (<$compiler>) {
> chomp;
> @cmplr_data = (split(/:/))[0,1,2,4,5,6];
> ($cusername, $cpswd, $cuid, $cgecos,
> $chome, $cshell) = @cmplr_data;
> push(@{$compiler_data{$cuid}}, $cusername,
> $cpswd, $cgecos, $chome, $cshell);
You're right; this will put all the user information for both
compilers in one hash. If someone's password information
differs between compilers, you'll lose part of it.
> }
> close ($compiler) or die "Can't close file
> $compiler_passwd: $!\n";
You can usually omit the error check on file close, unless the
status is of great interest.
I'm not quite certain how you intend to index the information; I
think you mean to have a separate store of user fields for
each combination of system and compiler name. If so, this should
do:
use warnings;
use strict;
use FileHandle;
our %compilers = (
system1 => ["compiler_a"],
system2 => ["compiler_b", "compiler_c"],
system3 => ["compiler_d"],
);
sub get_cinfo
{
my $system = shift;
my %cinfo;
foreach my $compiler (@{$compilers{$system}})
{
my $passwdfile = $compiler . "_passwd";
my $fh = new FileHandle ($passwdfile, "r")
or die "Can't open file $passwdfile: $!\n";
# lines presumably have name:passwd:uid:gid:gecos:home:shell
# want uid to index (name, passwd, gecos, home, shell)
while (my $line = $fh->getline()) {
chomp $line;
my ($uid, @info) = (split(/:/, $line))[2,0,1,4,5,6];
$cinfo{$compiler}{$uid} = \@info;
}
$fh->close();
}
return \%cinfo;
}
# Example: fetch user info for compiler_b on system2.
my $userhash = get_cinfo("system2")->{compiler_b};
while (my ($user, $info) = each %$userhash) {
print "$user: @$info\n";
}
--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]