Path: utzoo!utgpu!news-server.csri.toronto.edu!clyde.concordia.ca!uunet!etnibsd!vsh From: vsh@etnibsd.UUCP (Steve Harris) Newsgroups: comp.lang.perl Subject: pwd in perl Message-ID: <1141@etnibsd.UUCP> Date: 7 Aug 90 17:22:12 GMT Organization: Eaton Corp, Semiconductor Equipment Div., Beverly, MA Lines: 57 Here is a simple-minded implementation of pwd in perl. It's not too fast, but neither is "chop($cwd = `pwd`);" The path to the current directory is returned in an array, which is passed by reference. Any critiques of the algorithm (essentially, walk up the directory tree till you reach the root) will be appreciated. Steve Harris - Eaton Corp. - Beverly, MA - uunet!etnibsd!vsh =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=- ;# pwd.pl -- perl library function ;# ;# usage: ;# die "error in pwd" unless &pwd(*path); ;# print "/", join('/',@path), "\n"; sub pwd { local(*path) = @_; # array to hold path (return value) local($dc,$ic); # dev, ino for parent dir local($dp,$ip); # dev, ino for child dir local($d,$i,$f); # tmp: dev, ino, file name @path = (); # init path ($dc,$ic) = stat('.'); # get initial child_dir info outerloop: for (;;) { ;# chdir to parent_dir unless (chdir('..')) { warn "cannot chdir .., path = ", join('/', @path); return 0; } ;# get parent_dir info ($dp,$ip) = stat('.'); unless (opendir(D,'.')) { warn "cannot opendir ., path = ", join('/', @path); return 0; } ;# look for entry in parent_dir with same dev, ino as child while ($f = readdir(D)) { next if $f eq '..'; # skip '..' next if -l $f; # skip links (but do lstat!) next unless -d _; # skip non-dirs ($d,$i) = stat(_); # get dev, ino for dir next unless ($d == $dc && $i == $ic); # match? last outerloop if ($f eq '.'); # root dir? unshift(@path,$f); # add dir to path ($dc,$ic) = ($dp,$ip); # parent becomes next child last; # exit readdir loop } closedir(D); } 1; } -- Steve Harris - Eaton Corp. - Beverly, MA - uunet!etnibsd!vsh