#! perl # Check command line argument(s) if ( !@ARGV[0] or @ARGV[1] or !( @ARGV[0] =~ m/^[-\w]+(\.\w+)?$/ ) ) { print "\nWhich.pl, Version 2.00\n"; print "Locate the specified program file\n"; print "Port of Unix' WHICH command\n\n"; print "Usage: WHICH.PL filename[.ext]\n\n"; print "Where: \"filename\" is a file name only: no path, no wildcards\n\n"; print "Note: This script ignores DOSKEY macros and internal commands, and\n"; print " returns external commands (executable or script file names) only.\n\n"; print "Written by Rob van der Woude\n"; print "http://www.robvanderwoude.com\n"; exit(2); } # Store PATH and PATHEXT in arrays while ( ( $key, $value ) = each %ENV ) { if ( uc( $key ) eq "PATH" ) { # Current directory must be searched before the PATH @path = ( ".", split( /;+/,$value ) ); } elsif ( uc( $key ) eq "PATHEXT" ) { # Search for "non-executable" program files too @pathext = ( split( /;+/,$value ) ); } } # Search code in labelled block, to allow quitting the loop SEARCH: { # Search each directory specified in PATH foreach ( @path ) { $d = $_; # Remove trailing backslash or backslash plus dot $d =~ s/^(.*)\\\.?$/\1/; # Read the directory (files only) opendir( SEARCHDIR, $d ) or die "Cannot open directory $d:\n$!"; readdir ( SEARCHDIR ); @files = grep { -f "$d\\$_" } readdir( SEARCHDIR ); foreach $file ( @files ) { # Check for specified file name both with # and without each extension from PATHEXT if ( @ARGV[0] =~ m/^[^.]=\.[^.]+$/ ) { if ( $file =~ m/^@ARGV[0]$/i ) { # Display result print "\n$d\\$file\n"; # Close directory handle closedir( SEARCHDIR ); # Abort search at first successful find last SEARCH; } } else { foreach $ext ( @pathext ) { if ( $file =~ m/^@ARGV[0]($ext)$/i ) { # Display result print "\n$d\\$file\n"; # Close directory handle closedir( SEARCHDIR ); # Abort search at first successful find last SEARCH; } } } } # Close directory handle closedir( SEARCHDIR ); } # If you arrived here, the search was unsuccessful print "\n-None-\n"; exit(1); }