8/12 I am not a techie but I am trying to learn some perl to do
some text manipulation for my research. I am having trouble
with hashes. Can someone give me an example of how to read
in something like the password file (say, user, directory, shell)
into a hash?
\_ The question belies a slight misunderstanding of hashes. A hash
is a simple set of key value pairs, so reading a password file
in would require a bit of thought to the structure. You could
make the key be uid and the value be a pointer to an array of
the passwd line, i.e. (username,pw,uid,gid,gcos,hdir,shell).
You could alternately key on username. You could make an array
of hash references where each array member is like
username => 'root',
pw => '*',
uid => 0,
gid => 0,
etc. But using a single 1-dimensional hash on something like
an entire passwd file would yield you the data from the last
line in the file.
\_What would be the right structure to use to read in the
whole password table and hold it in a structure so I could
refer to some arbitrary piece of data like "the shell of
user user1"? Like if I wanted to merge the encrypted password
from the shadow file with the login and shell fields from the
password file? Thanks for your explanation.
\_ Now that you could do with a hash, but easier would be to use
(getpwnam('user1'))[8] to get the shell. But to do this for
the whole passwd file (as an example) would be
open PW,'/etc/passwd';
my %shells;
foreach my $pwentry (<PW>) {
chomp $pwentry;
($name,$shell) = (split /:/,$pwentry)[0,6];
$shells{$name} = $shell;
}
close PW;
Oh wait. I didn't catch the part about shadow password, but
this should give you an idea of where to start. |