#!/usr/bin/perl
#
#NAME
#  which.pl - Show executables in the search path
#
#SYNOPSIS
#  which.pl [-a] [pattern]..
#
#DESCRIPTION
#  Find executables in the search path whose names match any  of  the
#  pattern(s).
#
#  Note that the pattern is a "glob" pattern, not a RE.  Matching  is
#  done by your $SHELL program, not by perl's pattern match.
#
#  Only programs executable by the current uid/gid are shown.
#
#OPTIONS
#
#  +a
#  -a
#  --all
#    Show all the matching files, not just the first one.
#
#EXAMPLES
#
#  which.pl -a '[Ww]here*' '[Ff]ind*'
#
#    Show all executables in the search path whose names  start  with
#    '[Ww]here' or '[Ff]ind'.
#
#  which.pl '[Ww]here*' '[Ff]ind*'
#
#    Similar, but for each matching name, only the first is shown.  
#
#FILES
#
#BUGS
#  This doesn't show shell builtins, of course.  So if you're  trying
#  to  find  out  "If  I  were to type a 'foo' command, which program
#  would run, this program will give an incorrect answer  when  'foo'
#  is a builtin command in your shell.
#
#  Maybe we should add an option to do RE matching, too.
#
#SEE ALSO
#  which(1)
#
#AUTHOR
#  © 1998, 2003 John Chambers <jc@trillian.mit.edu>
#  This may be used freely by anyone under the terms of the GPL.
#  If you add any useful features, please send me a copy.

$| = 1;
@path = split(':',$ENV{'PATH'});

for $arg (@ARGV) {
	if ($arg =~ /^[-+]+a/i) {
		++$showall;
		next pattern;
	}
	for $dir (@path) {
file:	for $f (glob("$dir/$arg")) {
			$f =~ s"^$dir/*"";	# Bare file name.
			next file if ($found{$f}++ && !$showall);
			print "\t$dir/$f\n" if -x "$dir/$f";
		}
	}
}
