Perl getpwnam fails in sub

405 Views Asked by At

So i'm trying to use getpwnam() to search etc/passwd for a username in a sub, and return true if it exists. I keep getting the error "Use of uninitialized value in getpwnam".

sub nameSearch
{
$search = $_;
@name = getpwnam($search);
if ( ! defined $name[0])
{
return 0;
}
else
{
return 1;
}
}

I'm passing a chomped string into this sub. I've tried just using @name = getpwnam($_[0]) and @name = getpwnam($_)

I know as a fact that string i'm passing exists as a username in /etc/passwd and the code works when its not in a sub.

1

There are 1 best solutions below

0
On BEST ANSWER

If you're passing user name as a parameter then you should check first element of @_ which is $_[0].

$_ is global variable conveniently used as implicit foreach variable and function can use it in case no parameter was sent to it. Actually this is common behavior for most perl core functions which take $_ if no explicit argument is given.

sub nameSearch {
  my ($search) = @_;
  $search = $_ if !@_;

  my @name = getpwnam($search);

  return @name ? 1 : 0;
}

print nameSearch("user") ? "exist" : "doesn't exist";