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.

Need Your Help

Qt Symbian Fonts

qt fonts symbian qml ovi

I have created a Qt app for the Nokia Ovi store but I know want to update the font int the QML file, but just changing it in the designer doesn't change it on the symbian device. I have checked goo...

SDL in Visual C++ - where to properly put images used in the program?

visual-c++ sdl

I'm just learning SDL and I would like to know where is the correct place to put images and other file stuff in?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.