Why you should use getcwd and not cwd

The Cwd module provides several functions for finding the current directory. The most similar-seeming are cwd and getcwd. Have you ever wondered why you should pick one or the other?

I always use getcwd and I'll show you why.

My ~/.dzil directory is a symlink to a git repository elsewhere. If I'm in that directory in my terminal, here is a look at three ways to get the current path:

$ perl -MCwd=cwd,getcwd -MFile::Spec -wE 'say for cwd(), getcwd(), File::Spec->rel2abs(".")'

The cwd call returns the symlink path — the way the shell sees it. The getcwd call returns the real path with the symlink resolved.

Now look at the third. That's from File::Spec. A LOT of code uses File::Spec to manipulate paths. If you ever want to compare the current directory against a path made absolute by File::Spec, you need to use getcwd.

I've found that getcwd is more consistent across platforms, whereas cwd can be implemented differently depending on your platform or if you have XS or pure-perl implementations.

I like consistency.

Sure, there are cases where the "shell view" of the current directory is more important and you might want to use cwd, but I find that is the exception, not the rule.

Consistency matters. Use getcwd.

This entry was posted in perl programming and tagged , , . Bookmark the permalink. Both comments and trackbacks are currently closed.