Mike
Mike

Reputation: 60802

How can I map UIDs to user names using Perl library functions?

I'm looking for a way of mapping a uid (unique number representing a system user) to a user name using Perl.

Please don't suggest greping /etc/passwd :)

Edit

As a clarification, I wasn't looking for a solution that involved reading /etc/passwd explicitly. I realize that under the hood any solution would end up doing this, but I was searching for a library function to do it for me.

Upvotes: 4

Views: 3745

Answers (3)

Escualo
Escualo

Reputation: 42132

Read /etc/passwd and hash the UID to login name.

Edit:

$uid   = getpwnam($name);
$name  = getpwuid($num);
$name  = getpwent();
$gid   = getgrnam($name);
$name  = getgrgid($num);
$name  = getgrent();

As you can see, regardless of which one you pick, the system call reads from /etc/passwd (see this for reference)

Upvotes: 1

P Shved
P Shved

Reputation: 99344

The standard function getpwuid, just like the same C function, gets user information based on its ID. No uses needed:

my ($name) = getpwuid(1000);
print $name,"\n";

Although it eventually reads /etc/passwd file, using standard interfaces is much more clear for other users to see, let alone it saves you some keystrokes.

Upvotes: 8

nc3b
nc3b

Reputation: 16240

Actually I would suggest building a hash based on /etc/passwd :-) This should work well as the user ids are required to be unique.

Upvotes: 0

Related Questions