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

Is there a nice (read terse and few/no blocks) means of retrieving the GIDs of all the groups a member is in?

(getpwuid($<))[3]

Only returns the first. Ideally it should be useable as:

$) = expression

Thanks!

Replies are listed 'Best First'.
Re: Fetching groups a user is in
by Kanji (Parson) on Oct 11, 2001 at 19:52 UTC
      Seems like there ought to be something simpler though...

      $) = &{sub{ my(@F,@G); while( @F = getgrent() ){ push(@G, $F[2]) if $F[3] =~ /\b$ENV{USER}\b/; } return join(' ', @G); } };
      Well yeah, but I was hoping I wouldn't have to muck with getgrent... but I suppose if I did an anonymous sub...

      $) = sub { #iterate over getgrent, save gid of group that $) belongs to. return join(' ', @F); }

      Seems so unclean though

        Nope wait, doesn't like <CODE>= sub { ..}</CODE, damn!
Re: Fetching groups a user is in
by jlongino (Parson) on Oct 11, 2001 at 21:07 UTC
    The easiest thing to do is use the xnix (provided you are using an xnix box) command groups:
    my @groups = `groups $username`; print join "\n", @groups;
    This normally doesn't require any special priviledges.

    Update: Then determine the GIDs of course.

    "Make everything as simple as possible, but not simpler." -- Albert Einstein

Re: Fetching groups a user is in
by apotheon (Deacon) on Dec 21, 2006 at 22:05 UTC

    Obviously, I'm a little late to this party, but I stumbled across this while checking to see whether I'd have to (re)invent a wheel to answer a question on the Perl Beginners mailing list. This is the solution I ultimately came up with:

    #!/usr/local/bin/perl -l use strict; use warnings; my $user = $ARGV[0]; my @gr_list; my @pw_info; while (@pw_info = getpwent) { if ($pw_info[0] eq $user) { my @gr_info; while (@gr_info = getgrent) { push(@gr_list, $gr_info[2]) if ($gr_info[3] =~ /\b$user\b/); } push(@gr_list, $pw_info[3]); } } print foreach @gr_list;

    It's not stunningly terse or clean-looking, at least in my estimation, but it works and doesn't involve calling out to external system utilities.

    print substr("Just another Perl hacker", 0, -2);
    - apotheon
    CopyWrite Chad Perrin

      I saved the code as gpu.pl and ran it for some users:
      $ gpu.pl root 0 2 3 4 5 20 31 0 $ gpu.pl rvtol $ id -Gn rvtol user
      With root, group 0 is reported twice. With rvtol, group user (30) isn't reported.

      -- 
      Regards, Ruud

        Interesting. Any idea why?

        print substr("Just another Perl hacker", 0, -2);
        - apotheon
        CopyWrite Chad Perrin