A quick snippet that reliably but quickly returns a username for the current real user ID, taking into consideration possible multiple login names for a given user ID. Guaranteed not to return a username with different privileges, but might not return the precise username that was used to log in.
sub whoami { for ($ENV{USER}, $ENV{LOGNAME}, getlogin()) { if (getpwnam($_) == $<) { ## is this a matching uid? return $_; ## return that name } } return scalar getpwuid($<); ## fallback, return name for this ui +d }