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

I need to open up my /etc/passwd file by name and print out the user name and user id. Here is my way of opening up all the ids and names in unix but I need to write a perl script to open it by name and print out the user name and user id.
cat /etc/passwd | awk -F: '{print $1,$5}'

Replies are listed 'Best First'.
Re: Opening file and printing specific data
by Abigail-II (Bishop) on Jun 06, 2002 at 15:12 UTC
    #!/usr/bin/perl use strict; use warnings 'all'; my ($name, $uid, $passwd); print "$uid: $name\n" while +($name, $passwd, $uid) = getpwent; __END__

    Abigail

Re: Opening file and printing specific data
by Beatnik (Parson) on Jun 06, 2002 at 14:54 UTC
    Try...
    print ((getpwnam "username")[0,2]); #$ENV{USER} for example
    Check the POD for getpwnam for the list of return values...
    Small Update: 0 is the username, 2 is the uid :)
    Update2: oki, so this doesn't take ALL the users... use getpwent like Abigail-II showed below

    Greetz
    Beatnik
    ... Quidquid perl dictum sit, altum viditur.
      Thank you all for your answers.
Re: Opening file and printing specific data
by Aristotle (Chancellor) on Jun 06, 2002 at 19:49 UTC
    Why the cattiness? awk -F: '{print $1,$5}' < /etc/passwd Or in Perl, perl -naF: -e'print "@F[0,4]\n"' /etc/passwd *grin*

    Makeshifts last the longest.

Re: Opening file and printing specific data
by Joost (Canon) on Jun 06, 2002 at 14:55 UTC
    <IGNORE> system "cat /etc/passwd | awk -F: '{print $1,$5}'";

    But seriously

    open PWD,"</etc/passwd" or die "Cannot open: $!"; while (<PWD>) { my ($name,$id) = (split /:/)[0,4]; print "$name,$id\n"; } close PWD;
    </IGNORE>

    Update: i didn't read this very well, did I? .. The above reply is correct. This one isn't.

    Sorry...

    -- Joost downtime n. The period during which a system is error-free and immune from user input.