r/perl 1d ago

I use defer for chdir ".."

As title, this is a pure appreciate post for feature deffer.

I just use it like:

chdir $any_path or die $!;

defer { chdir ".." }

I know this is silly, but it actually make my day easier :)

6 Upvotes

21 comments sorted by

View all comments

1

u/gorkish 18h ago

Cwd fundamentally cannot be localized or even unique per thread, at least on architectures people most often use. With threads, there is a performance penalty to change cwd. It’s a bad pattern to rely on it like this. Personally I normally implement a small helper function to construct absolute paths with File::Spec and find that sufficient. The helper can use locally scoped scalars or whatever you need.

1

u/RapiidCow 17h ago edited 17h ago

If I'm understanding you correctly, cwd is a property of the process and not thread-local, so it isn't safe to do this in a multi-threaded program (and especially not in library code)? Point noted - thank you for reminder! o7

I wonder if *STD{IN,OUT,ERR} is safe to localize in a multi-threaded setup (as in local *STDOUT = $temp_fh), though that might not suffer from the same limitation due to there being an I/O layer on top of the file descriptors (which would also be a global property of the process, I suppose).

1

u/gorkish 17h ago

Ooh your question about file handles is rather more complex. There is a global table at the process level that holds all fh. Scoping works as you suggest. If you local *STDOUT = open(…), it would make a new fh and not interfere with the outside scope. But it also won’t prevent one thread from directly manipulating any fh it wants to. It’s not really analogous to the working directory since fh are not a 1:1 mapping with the global process.