Joe Sewell
Joe Sewell

Reputation: 306

How do I open a file in Perl using a search path (e.g. $PATH)?

I have a situation in which I am reading filenames from a file in Perl. These filenames never have a directory associated with them, only a file name (e.g. "foo.bar"). I need to search the equivalent of gmake's VPATH (or a shell's PATH) for that file.

I figure I can split the PATH at the colons, concatenate each segment to the file, and see if it exists. Is there an easier way to do this, though?

Upvotes: 0

Views: 197

Answers (1)

choroba
choroba

Reputation: 241858

What's so uneasy in it?

#! /usr/bin/perl
use warnings;
use strict;

use List::Util qw{ first };

sub find_in_path {
    my $file = shift;
    return first { -f } map "$_/$file", split /:/, $ENV{PATH}
}

print find_in_path('grep'), "\n";

Upvotes: 4

Related Questions