How can I get the primary and other groups of the currently logged on user in Perl?
According to this site I can simply write
$user = getlogin();
but the group handling functions seem not to be able to accept a username/userid as a parameter. Should I really iterate over all the /etc/group file lines and parse the group names from it?
No need to parse system files, on an UNIX-like operating system I would use the builtin interfaces to the getpwuid and getgrgid system calls:
use strict; use warnings; # use $< for the real uid and $> for the effective uid my ($user, $passwd, $uid, $gid ) = getpwuid $< ; my $group = getgrgid $gid ; printf "user: %s (%d), group: %s (%d)\n", $user, $uid, $group, $gid;
Something simpler like
my $group = getgrgid $(
would also work, since $( and $) already should contain the GID and the EGID.
Finally the getgroups function defined in the POSIX module,
use POSIX qw(getgroups)
as suggested by dsw, should also allow you to get the secondary groups, if your OS (unlike, for example, Linux) supports having multiple active groups at the same time.
Finding inactive secondary groups might indeed involve parsing the /etc/group file, ither directly or via the combined usage of the getgrend builtin and the standard User::grent module.