Here's the reason why I'm asking this question: I write a lot of bash and Perl scripts, and I find myself having to concatenate two paths every so often. Something like this is typical:
my $prefix = "/home/user/";
my $suffix = "/mystuff";
...
chdir $prefix.$suffix;
The problem is that I don't always remember if I put a slash at the end of the prefix, or if I put a slash at the beginning of the suffix. So I could accidentally concatenate two slashes together, like in the above example.
So my main question is whether or not two consecutive slashes will cause any problems and why. But also, do programmers have a convention for this? In the code that other people write, do directory names always end with a slash? It would be nice if there is some consistent rule that I could follow.
It's perfectly fine. Repeated slashes are treated as one by Unix systems, so always add one.
my $prefix = "/home/user"; # Or "/home/user/"
my $suffix = "mystuff";
my $dir = "$prefix/$suffix";
But if you want a canonised path for whatever reason (e.g. it's going to be displayed to a user), you can use:
use Path::Class qw( dir );
my $prefix = dir("/home/user"); # Or "/home/user/"
my $dir = $prefix->subdir($suffix);
say $dir;
Whether you start with /home/user
, /home/user/
or even ///home///user///
, you end up with:
/home/user/mystuff
Unix shells and kernels happily handle this, as well as things like "/firstpart/./secondpart", but generally you don't make trailing slash a part of the variable value to make path concatenation expressions look nicer: ${firstpart}/${secondpart} rather than ${firstpart}${secondpart}.
In scripts on Linux the readlink command line tool can be used to normalize file names.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With