ovedpo15 has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,
I have a bunch of paths and for each path I want to convert it from relative path to absolute path. For that I use the rel2abs method. But I noticed a corner case where I have a path that starts with tilda ~. In that case I get:
rel2abs ~/.test /abc/site/disks/home_user/asdas/~/.test
Where the actual path is:
/abc/site/disks/home_user/asdas/.test
How do I treat this special case?

Replies are listed 'Best First'.
Re: rel2abs of a path with tilde (updated)
by haukex (Archbishop) on Jun 06, 2021 at 15:40 UTC
    I have a bunch of paths and for each path I want to convert it from relative path to absolute path.

    Have a look at Path::ExpandTilde. Note that the resulting path will be dependent on the system this function is being run on and the current username.

    Update: Note the docs of File::Spec's rel2abs: "No checks against the filesystem are made." But if you don't mind going out to the filesystem, you can also use Cwd's abs_path.

Re: rel2abs of a path with tilde
by LanX (Saint) on Jun 06, 2021 at 13:28 UTC
    ~ means $ENV{HOME} on most systems.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    Wikisyntax for the Monastery

    update

    corrected typo s/tilda/tilde/ for searchability, sorry Tilda ...

      Yes that I know. The question is, do I need to handle it myself (replace ~ with $ENV{HOME}) or is there a better way to do it?
        Yes, after replacing it's not a relative path anymore.

        Most probably there is a module doing all this.

        Look into File::Path and similar namespaces on CPAN

        EDIT

        have a look into Path::Tiny, it seems to do the job

        Cheers Rolf
        (addicted to the Perl Programming Language :)
        Wikisyntax for the Monastery

Re: rel2abs of a path with tilda
by linuxer (Curate) on Jun 06, 2021 at 16:44 UTC

    This looks strange to me... I wonder on which system and in which shell you are doing this.

    It looks like rel2abs is - on your system - a shell command (I don't have it). So I assume you are testing in the shell.

    IMHO: Your shell should handle the expansion of ~ to the correct path. If it does not, try to fix your shell or try a different shell.

    Tests in my shell (/bin/bash):

    $ perl /tmp/t.pl ~/.vimrc ~user/.vimrc ~root/.vimrc /home/linuxer/.vimrc /home/user/.vimrc /root/.vimrc
    /tmp/t.pl:
    #! /usr/bin/env perl use strict; use warnings; use 5.020; say $_ for @ARGV;
      Hi I'm sorry that my example was not intuitive. I meant that I use perl's rel2abs sub. I used Path::Tiny and it solve the problem. Thank you!