How would you get the current user’s name in your programming language of choice? Furthermore, how does this exercise reflect on the design of that language?
C#
string user = Environment.UserName;
Perl
my $user = getpwuid($<);
PHP
$user = $_ENV['user'];
Python
import os
user = os.environ['USER']
Ruby
user = ENV['USER']
Now that I’ve iterated through a few of these I’m wondering if the methods are equivalent. In every language except Perl it seems like I’m just accessing the ‘user’ property of the current environment variables. Is there a better way to get the name of the current user in those other languages? I read a perldoc1 that says getpwuid is the best method in Perl.


Applescript
set user to system attribute "USER"Use inline C and call geteuid(). :)
This is a very late response, but . . .
In Ruby:
require 'etc'
user = Etc.getpwuid.name
Etc is part of the standard/core library of Ruby. Etc.getpwuid returns a bunch of information about the current user (or you can specify a specific user as an argument). A number of methods pick out specific parts of that information, such as name (as above), dir (for the user’s home directory), and so on.
Notice on Python:
On my System (WinXP, Py2.4.3) I have no “USER” key. Instead I have to use the “USERNAME” key.
Greetz