in reply to Passing Regex Pattern in Subroutine
Bug: Your get_data() returns only the last hit (e.g. for james).
FWIW, see also:
Maybe it is easier to read /etc/passwd (root: /etc/shadow too) into a hash once and then access the hash by user-id?
use strict; use warnings; use Data::Dumper; my @items = qw(name passwd uid gid quota comment gcos dir shell expire +); my %user_data; # Slurp /etc/passwd once and create hash. # When executed as root, entry 'passwd' will be visible (not 'x'). while ( my @pwdata = getpwent ) { my $name = $pwdata[0]; $user_data{$name} = { map{ $_ => shift @pwdata } @items }; } # DONE! The rest is example code. # see full datastructure # print "Dump: \n", Dumper(\%user_data), "\n"; # sample output my $name = 'root'; print "=== $name ===\n"; print Dumper( $user_data{ $name } ),"\n"; print "shell: $user_data{$name}{shell}\n"; __END__ === root === $VAR1 = { 'quota' => '', 'uid' => 0, 'name' => 'root', 'dir' => '/root', 'passwd' => 'x', 'comment' => '', 'shell' => '/bin/bash', 'expire' => undef, 'gid' => 0, 'gcos' => 'root' }; shell: /bin/bash
...or find a CPAN module that suits your requirements.
Update: This example covers the get_data() part of your question.
use strict; use warnings; use Data::Dumper; my @items = qw(name passwd uid gid quota comment gcos dir shell expire +); my %user_data; # Slurp /etc/passwd once and create hash. # When executed as root, entry 'passwd' will be visible (not 'x'). while ( my @pwdata = getpwent ) { my $name = $pwdata[0]; my $pw_line = join(':', @pwdata); # reconstruct passwd-line $user_data{$name} = { map{ $_ => shift @pwdata } @items } +; $user_data{$name}{pw_line} = $pw_line; } # see full datastructure # print "Dump: \n", Dumper(\%user_data), "\n"; # sample output my $name = 'root'; print "=== $name ===\n"; print Dumper( $user_data{ $name } ),"\n"; print "shell: $user_data{$name}{shell}\n"; # find users where regex matches sub get_data { my $regex = shift; return sort grep { $user_data{$_}{pw_line} =~ /$regex/ } keys %user_ +data; } print "Bash-Users: ", join(", ", get_data( qr{/bin/bash} )) , "\n"; __END__ === root === $VAR1 = { 'quota' => '', 'uid' => 0, 'name' => 'root', 'dir' => '/root', 'passwd' => 'x', 'pw_line' => 'root:x:0:0:::root:/root:/bin/bash', 'comment' => '', 'shell' => '/bin/bash', 'expire' => undef, 'gid' => 0, 'gcos' => 'root' }; shell: /bin/bash Bash-Users: at, bin, daemon, ftp, lp, man, news, nobody, root, uucp </readmore>
|
|---|