Paths in Perl

Discussion in 'Perl' started by pradeep, Oct 17, 2005.

  1. pradeep

    pradeep Team Leader

    Joined:
    Apr 4, 2005
    Messages:
    1,645
    Likes Received:
    87
    Trophy Points:
    0
    Occupation:
    Programmer
    Location:
    Kolkata, India
    Home Page:
    http://blog.pradeep.net.in
    Different Operating Systems use different characters as their path separator when specifying directory and file paths:

    foo/bar/baz # *nix uses a /
    foo\bar\baz # Win32 uses a \
    foo:bar:baz # Mac OS 9 uses a :
    foo/bar/baz # Mac OS X uses a / (usually!)

    In Perl you can generally just use a / as your path separator (except on Mac OS 9, thanks Hanamaki). Why? Because Perl will automagically convert the / to the correct path separator for the system it is running on! This means that coding Windows paths like this

    $path = "\\foo\\bar\\baz";

    is not required. You can just use this:

    $path = "/foo/bar/baz";

    and things will be fine. In fact using \\ can be problematic, but you probably already know that :)

    If you want to display the expected system delimiter to a user (ie hide the fact that you are using / internally) you can just do something like this:

    Code:
    my $perl_path = '/foo/bar/baz';
     (my $win_path = $perl_path) =~ tr!/!\\!;
     print "Perl still sees: $perl_path\n";
     print "But we can print: $win_path\n";
     
    If you need to do lots of conversions just write a sub like this:
    Code:
     my $perl_path = '/foo/bar/baz';
     print "This is the Windows path: ", win_path
     ($perl_path), "\n";
     
     sub win_path {
     (my $path = shift) =~ tr!/!\\!;
     return $path;
     }
    So there you have it. Paths in Perl. By using a / you make it much easier to port your code to another system.
     
    Last edited by a moderator: Apr 25, 2006

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice