How do I get the current user in Perl in a portable way?

27,227

Solution 1

getlogin:

This implements the C library function of the same name, which on most systems returns the current login from /etc/utmp, if any. If null, use "getpwuid".

$login = getlogin || getpwuid($<) || "Kilroy";

Do not consider "getlogin" for authentication: it is not as secure as "getpwuid".

You can also try ||-ing this with POSIX::cuserid() and Win32::LoginName().

Solution 2

Win32::LoginName() can be used on Windows to retrieve the user name (without the domain name, so it may be ambiguous):

use Win32;
my $username = Win32::LoginName;

Win32::pwent implements getpwuid() and other features to query the user database. Unfortunately, it failed to install on my StrawberryPerl 5.12.

Share:
27,227
Dan Dascalescu
Author by

Dan Dascalescu

Bio Co-founded the visa-free startup ship, Blueseed, the Quantified Self Forum (a community for self-trackers), and two web startups using meteor. Former Developer Advocate at Google - Progressive Web Apps (PWA), Accelerated Mobile Pages (AMP), Chrome OS, and AR (Lens). Former localization engineer at Yahoo!. I currently discourage localization in general, for reasons I haven't seen successfully challenged since 2009, with the exception of translating basic computer programming materials as a way to onboard new developers. More about me on on Wikipedia or on my website. My CV is on StackOverflow Careers. Interests Entrepreneurship and disruptive technologies, biotech, 3D printing, brain-computer interfaces, prediction markets. Applying ~20 years of experience in software development and ~5 in the startup world in CTO roles at emergent tech companies.

Updated on February 15, 2020

Comments

  • Dan Dascalescu
    Dan Dascalescu over 4 years

    How does one get the current user in a portable way?

    This seems like an FAQ but perlport doesn't speak about it, maybe because some odd systems don't have the concept of "user" to being with? However, let's stick to *nix and Windows.

    getpwuid($>) is not implemented on Windows.

    $ENV{USER} || $ENV{USERNAME} seems finicky.

    http://search.cpan.org didn't turn up much.

  • ysth
    ysth over 13 years
    If you have switched users with su, getlogin will return the original user, something that would be an unpleasant surprise to me as a user; just use getpwuid for posixy systems and Win32::LoginName for windows.
  • Ether
    Ether over 13 years
    @ysth: good to know. I expect this is what the docs were alluding to in "Do not consider..for authentication".