Operating System - HP-UX
1820260 Members
2947 Online
109622 Solutions
New Discussion юеВ

looping through two arrays at once in perl

 
ROSS HANSON
Regular Advisor

looping through two arrays at once in perl

Hello,
I am trying to write a script, in perl, in which the script will ask me to type in the names of users to find in the /etc/passwd file. The names I type in will be placed into an array. I then want the program to loop through the array ( with the names I typed in) and compare those names with the names in the
/etc/passwd file. This, I believe, will require the use
of two looping scripts going at once. I am having
a problem producing such a script any idea?????
Ross Hanson
3 REPLIES 3
Rodney Hills
Honored Contributor

Re: looping through two arrays at once in perl

A hash variable would work best for that. example-

@users=(joe,ralph,sally);
map {%usersx{$_}=1} @users;
open(INP,"while() {
($user)=split(":",$_);
if ($usersx{$user}) {
... this is a matching user from list
}
}

-- Rod Hills
There be dragons...
Rodney Hills
Honored Contributor

Re: looping through two arrays at once in perl

Small mistake on my part

The line-
map {%usersx{$_}=1} @users;

Should be-
map {$usersx{$_}=1} @users;

-- Rod Hills
There be dragons...
Ralph Grothe
Honored Contributor

Re: looping through two arrays at once in perl

Hi Ross,

not that I want to dissuade you from using nested loops, but Perl has many builtin functions especially related to Unix (since it is a Unix child)
You should use the getpw* functions Perl offers to this end.
Read the POD of e.g.

perldoc -f getpwnam

Say we have read from stdin these users (I deliberately took pseudo users here, because of the missing password string ;-)


@users = qw(nobody lp uucp larry smbnull randal tux);

foreach $user (@users) {
unless (@fields = getpwnam $user) {
print STDERR "Sorry, there is no user '$user' on this box\n";
} else {
print "User '$user' was assigned\n";
print "UID:\t$fields[2]\n";
print "GID:\t$fields[3]\n";
print "Home:\t$fields[7]\n";
print "Shell:\t$fields[8]\n";
}
}


The list elements returned by the getpw* functions are in the same order as the fields in /etc/passwd,
but consult the POD for details.
N.b. in scalar context the getpw* functions return only the first field, which is the user name.

HTH
Ralph
Madness, thy name is system administration