Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if file exists even on PATH

Tags:

perl

I have something like this:

if(! -e $filename) {
    # do something
}

but I need to alter it so that it looks for file even on my PATH. Is there any way to achieve this without analysing PATH?

like image 723
Adam Pierzchała Avatar asked Dec 07 '22 18:12

Adam Pierzchała


2 Answers

File::Which

like image 67
daxim Avatar answered Jan 03 '23 05:01

daxim


How can you see if a file is in one of the directories specified in $ENV{PATH} without looking at $ENV{PATH}? … That's a rhetorical question.

Here is a short script I wrote some time ago. You should be able to adapt it for your needs:

#!/usr/bin/perl

use strict; use warnings;

use File::Basename;
use File::Spec::Functions qw( catfile path );

my $myname = fileparse $0;
die "Usage: $myname program_name\n" unless @ARGV;

my @path = path;
my @pathext = ( q{} );

if ( $^O eq 'MSWin32' ) {
    push @pathext, map { lc } split /;/, $ENV{PATHEXT};
}

PROGRAM: for my $progname ( @ARGV ) {
    unless ( $progname eq fileparse $progname ) {
        warn "Not processed: $progname\n\tArgument is not a plain file name\n";
        next PROGRAM;
    }

    my @results;

    for my $dir ( @path ) {
        for my $ext ( @pathext ) {
            my $f = catfile $dir, "$progname$ext";
            push @results, $f if -x $f;
        }
    }

    print "$progname:\n";
    print "\t$_\n" for @results;
}
like image 45
Sinan Ünür Avatar answered Jan 03 '23 03:01

Sinan Ünür