Why is my getpwent () call returning the wrong user?

I always forget how to do this in Perl. Here's my script:

#!/usr/local/bin/perl -w
use strict;
use Data::Dumper;

my @got = getpwent();
my $username    = ${[getpwent()]}[0];

print Dumper( @got );
print "username is [$username]\n";

      

... and here is the result it produces ...

$VAR1 = 'root';
$VAR2 = 'xxxxxxxxxxxxxxxxxx';
$VAR3 = 0; 
$VAR4 = 0;
$VAR5 = ''; 
$VAR6 = '';
$VAR7 = 'myhost root';
$VAR8 = '/root';
$VAR9 = '/bin/bash';
username is [bin]

      

... and my question is, why is the username "bin" instead of "root"?

+3


source to share


2 answers


It iterates over users; you call it twice and you get information for two users.



$ perl -E 'say $foo while $foo = getpwent()'
root
daemon
bin
sys
sync
...

      

+5


source


Repeated calls getpwent

return different lines in the password file (or any other source of user information is used getpwent

).

root

is the first user listed in your password file bin

is the second.

Call endpwent

to reset the iterator and copy the previous calls to getpwent

:



for (0..2) {
    print scalar getpwent(), "\n";
}
print "-- reset --\n";
endpwent();
for (0..3) {
    print scalar getpwent(), "\n";
}

      

(YMMV)

SYSTEM
LocalService
NetworkService
-- reset --
SYSTEM
LocalService
NetworkService
Administrators

      

+3


source







All Articles