in reply to ~username expansion

sub get_home_dir { return $ENV{'HOME'} unless @_; my ($userid) = @_; local *PASSWD; open(PASSWD, '<', '/etc/passwd') or die("..."); my ($record) = grep { $_->[0] eq $userid } map { [ split(':') ] } <PASSWD>; return $record && $record->[5]; }

Replies are listed 'Best First'.
Re^2: ~username expansion
by atcroft (Abbot) on Nov 01, 2004 at 02:13 UTC

    You may wish to look at the getpwnam() function to get the directory entry for you, such as in the following example:

    #!/usr/bin/perl -w use strict; ( my $name, my $passwd, my $uid, my $gid, my $quota, my $comment, my $gcos, my $dir, my $shell, my $expire ) = getpwnam('user'); # Insert '(undef)' if variable is undefined. foreach my $x ( \$name, \$passwd, \$uid, \$gid, \$quota, \$comment, \$gcos, \$dir, \$shell, \$expire ) { ${$x} = '(undef)' unless ( defined( ${$x} ) ); } printf <<OUTPUT, $name, $passwd, $uid, $gid, $quota, $comment, $gcos, $dir, + $shell, $expire; getpwnam() OUTPUT: name: %s passwd: %s uid: %s gid: %s quota: %s comment: %s gcos: %s dir: %s shell: %s expire: %s OUTPUT

    According to the docs for the function, a null list would be returned if the user did not exist.

    Hope that helps.

Re^2: ~username expansion
by Fletch (Bishop) on Nov 01, 2004 at 02:01 UTC

    It's better to use getpwnam rather than reading the password file by hand (for example if the machine uses NIS / YP and you're not on the master machine you'll miss accounts).