简体   繁体   中英

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 (eg "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?

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";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM