Search code examples
fileperlpathrelative-path

Perl - Dynamic/relative File Path - Website


I am building a website using perl etc and i am trying to open a file and print the contents of it on the site however i can't seem to make it work when using a relative file path...

    # Load our header.html template file
open (HEADER, "/xampp/htdocs/website/template/header.html") or die "Can't find header.html - check path...";
print (<HEADER>);

That works

However, I would prefer it if I could do something like this:

# Load our header.html template file
open (HEADER, "/template/header.html") or die "Can't find header.html - check path...";
print (<HEADER>);

Solution

  • If your full path is

    /xampp/htdocs/website/template/header.html
    

    And you're currently in /xampp/htdocs/website (this is where your script is located, or is chdired to), then you can just use the relative path:

    template/header.html
    

    For example

    open my $fh, "<", "template/header.html" or die $!;
    print <$fh>;
    

    Note the use of three-argument open with a lexical file handle, as well as including the error $! in your die statement.