开发者

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

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? Howe开发者_高级运维ver, 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.


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().


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜