HazySmoke HazySmoke -4 years ago 128
Perl Question

How does Unix read a path name with two consecutive slashes? (e.g. /home/user//mystuff)

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.

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download