Max Hampton
Max Hampton

Reputation: 1304

Open File From Partially Qualified Path in Perl

For an introductory web scripting class, I am working on a project written in Perl that deals with reading a file on the server. I need to collect a filename, open it, do some regex matching on the contents, and output results.

The filename input can come in multiple forms:

The first two cases work with a simple call to open:

...
$file = param('file');
open(FH, "<", $file) || die "Cannot open $file: $!";
while (<FH>) {
    # do stuff
}
...

The last case with the partially qualified path obviously dies. I looked at File::Find, but can't quite figure out how it works. Is that the right module for me to use? Should I be doing some sort of recursive thing to work backwards through the directory tree? Thanks in advance for any pointers.

Edit: My case is very specific to instructions given by my professor. I got it working through a loop:

...
$file = param('file');
$open = open (FH, "<", $file);
while (!defined $open) {
    chdir('..') or die "Can't chdir or open $file $!";
    $open = open (FH, "<", $file);
}

It is now opening case three above, and will fit the purposes of my assignment, despite it not being a solution that will work in broad cases.

Upvotes: 0

Views: 239

Answers (1)

ikegami
ikegami

Reputation: 385734

Opening dir3/dir4/file.txt will work fine if that's the correct path to the file.

>md "dir3"

>md "dir3/dir4"

>echo foo >"dir3/dir4/file.txt"

>perl -E"open(my $fh, '<', 'dir3/dir4/file.txt') or die($!); print <$fh>;"
foo

If it's not, then there's no way to know to what file it's referring without additional info.


Of course, that assumes the paths are relative to the current work directory. If those paths are relative to some other directory you can use the following:

use File::Spec::Functions qw( rel2abs );

my $fqfn = rel2abs($qfn, "/home/foo");
open(my $fh, '<', $fqfn) or die($!);

More specifically, if those paths are relative to the directory in which the script resides, you can use the following:

use FindBin               qw( $RealBin );
use File::Spec::Functions qw( rel2abs );

my $fqfn = rel2abs($qfn, $RealBin);
open(my $fh, '<', $fqfn) or die($!);

Upvotes: 1

Related Questions