Thursday, March 20, 2008

findpath

I originally implemented this script in Bourne shell, but decided to do it up in Perl this time. It simply searches $PATH for any binary matching the pattern you pass to it, case-insensitively. Albeit simple, it's very useful, at least to me.

findpath

#!/usr/bin/perl -w
use strict;
use warnings;
scalar @ARGV || die "Usage: $0 match\n";
my $match = shift @ARGV;
my @PATH = split(/:/, $ENV{PATH});
foreach(@PATH) {
print "$_\n" foreach(grep(/$match/i, (/\s/ ? <"$_"/*> : <$_/*>)));
}

One of my favorite parts about Perl is that it's easy to write very efficient scripts that look confusing to many.


Here's a slightly better version that searches only the basename of each file:

fpath

#!/usr/bin/perl -w
use strict;
use warnings;
scalar @ARGV || die "Usage: $0 match\n";
my $match = shift @ARGV;
my @PATH = split(/:/, $ENV{PATH});
foreach(@PATH) {
print "$_\n" foreach(grep(/$match[^\/]*$/i, (/\s/ ? <"$_"/*> : <$_/*>)));
}

No comments: