PDA

View Full Version : Doing stuff with hashes...


unruly
06-08-2002, 06:50 PM
well, I'm trying to make a program to get a username from the user, and use a hash to tell them what shell that user uses... useless, but it's for my own edification.... here's what I have so far. Right now I'm having problems getting info into/out of a hash....

#!/usr/bin/perl -w
sub getUserShell{
@etcPasswd = `cut -d: -f 1,7 /etc/passwd`; # easier than trying to figure out split ;)
foreach(@etcPasswd){
($user, $shell) = split(/:/, $_, 2);
chomp($user, $shell);
%userShell = { "$user" => "$shell" };
}
#return (print $userShell{"unruly"});
}
&getUserShell;

iDxMan
06-08-2002, 07:29 PM
Something similar to this should work:


#!/usr/bin/perl

sub getUserShell {
open(FILE,"/etc/passwd") or die "$!\n";
while(<FILE>) {
chomp;
my @line = split(/:/);
$userShell{$line[0]} = $line[6];
}
close(FILE);
}

getUserShell();

foreach $user (sort keys %userShell) {
print "$user -> $userShell{$user}\n";
}

l2kashe
08-21-2002, 04:42 PM
ok even

open(FILE,"/etc/passwd") || die "Cant access passwd\nReason: $!\n";

while (chomp($line = <FILE>)) {
($user,$shell) = (split(/:/,$line))[0,6];
$hash{$user} = "$shell";
}

while ( ($u,$s) = each(%hash) ) {
print "User: $u\tShell: $s\n";
}


/* Anyone reading this, can you explain why my spaces arent actuall indenting the code I would really appreciate a message or post on how to fix this. */

iDxMan
08-21-2002, 10:49 PM
Try surrounding your code with the `code` tags.


foo
indent foo
bar