http://www.perlmonks.org?node_id=1004999

dr.jekyllandme has asked for the wisdom of the Perl Monks concerning the following question:

Hello, I am writing a script that will find which user is executing the script. I found 3 different ways to do this:
#!usr/bin/perl use strict; use warnings; my $logname = $ENV{ LOGNAME }; print "\$logname = $logname\n"; my $user = $ENV{ USER }; print "\$user = $user\n"; my $pwuid = getpwuid( $< ); print "\$pwuid = $pwuid\n";
I noticed that for $ENV{ LOGNAME } and $ENV{ USER }, I can changes the variable value using setenv in csh and export in bash. But getpwuid's value always gives me the correct value. So should I go with getpwuid to get the correct user that is calling the script? Is there a better way? Thank you.

Replies are listed 'Best First'.
Re: What is the best way to find username running your script? (Windows)
by tye (Sage) on Nov 21, 2012 at 20:44 UTC

    I use $ENV{USERNAME} because it works on Unix and on Windows, IME. $ENV{LOGNAME} is probably the oldest one on the Unix side and so may be the most widely supported. You can even use something like $ENV{LOGNAME} || $ENV{USERNAME} || $ENV{USER} (assuming you don't let anybody have a username of "0").

    Of course, if you are worried about preventing people from pretending to be somebody else, then you shouldn't rely on an environment variable.

    - tye        

Re: What is the best way to find username running your script?
by tobyink (Canon) on Nov 21, 2012 at 20:14 UTC
    my $username = getpwuid($<);

    Not sure how well it does on MSWin32.

    perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Re: What is the best way to find username running your script?
by Anonymous Monk on Nov 22, 2012 at 04:18 UTC