mldvx4 has asked for the wisdom of the Perl Monks concerning the following question:

How can I retrieve a list of a POSIX group's members in Perl 5? I see some tantalizing hints involving getpwent, but need a more concrete example. This should be an easy question but I've not seen any answer I understand yet.

Replies are listed 'Best First'.
Re: Listing system group members
by choroba (Cardinal) on Mar 17, 2019 at 17:46 UTC
    I'm not sure about POSIX, but this seems to work on the systems I have access to (various Linux distributions):
    #!/usr/bin/perl use warnings; use strict; use feature qw{ say }; my $group = shift; my $gid = getgrnam $group; my @members = split ' ', (getgrgid $gid)[-1]; say "<$_>" for @members; while (my ($pwnam, $group_id) = (getpwent)[0, 3]) { say "[$pwnam]" if $group_id == $gid; }

    (Angle and square brackets added to emphasize the origins of the information)

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

      Nice solution; personally I prefer the OO User::pwent and User::grent:

      use warnings; use strict; use feature qw/say/; use User::grent; use User::pwent; my $grnam = shift; die "Usage: $0 GROUPNAME\n" unless length $grnam; my $group = getgrnam $grnam; die "Group '$grnam' not found\n" unless defined $group; say "<$_>" for @{$group->members}; while ( my $pwent = getpwent ) { say "[",$pwent->name,"]" if $pwent->gid == $group->gid; }

      Thanks! getgrgid was the function I needed:

      my $gid = getgrnam $group; my @members = split ' ', (getgrgid $gid)[-1];

      I now see where getgrgid is in the function manual, perlfunc(1). I'll have to read through that section until I get it.