in reply to Re: Following symlinks manually
in thread Following symlinks manually

This fragment follows the symlinks of $0 (the program name) to determine the home directory for the current program. While it's impossible for there to be a loop (the program got started, after all), the code does check for loops.

I'm not happy about the `pwd` dependency, but 'use Cwd' would have been longer and because I put this code in my BEGIN {} block, I wasn't sure if I could use 'use'. Also, it assumes '/' is the path separator and that \r and \n don't appear in the program pathname.

my $linkcount=50; (my $file=$0)=~s/.*\///; (my $HOME=$0)=~s/[^\/]*$//; $HOME||=`pwd`."/"; $HOME=~s/[\r\n]//g; while (defined(my $l=readlink($HOME.$file))) { if ($linkcount--<0) {die("$0: symlink loop detected, dying\n");} ($file=$l)=~s/.*\///; if (substr($l,0,1) eq "/") {($HOME=$l)=~s/[^\/]*$//;next;} (my $npwd=$l)=~s/[^\/]*$//; $HOME.=$npwd; }; print "The home directory for this program is $HOME\n";