This is the first of a set of novice challenges that I’ll present on this blog. I’ll give you some problem which you should be able to solve with just the stuff we present in Learning Perl. A week or so later, I’ll post a solution.
For your first problem, consider the which
command-line tool, which given a name, tells you the where in your PATH
it finds that program. With just a name, it tells you the first path it finds:
% which perl /Users/brian/bin/perls/perl
With the -a
switch, it shows all the paths:
% which -a perl /Users/brian/bin/perls/perl /usr/local/bin/perl /usr/bin/perl
This command takes an exact name. What if you don’t quite remember what the name is? This is your challenge.
Write a tool, called rhich
, which takes a pattern and searches through your PATH
looking for any program name that matches that pattern. Print all matching paths.
Since we don’t cover PATH
in Learning Perl, I’ll give you some hints.
PATH
is a set of directory names that the shell uses to search for a command to run. On Unix-like shells, the components are separated by colons. On DOS-like shells, it’s separated by a semicolon. You don’t need to do much work for that because perl
already knows what the separator is. The Config
module provides a %Config
hash with the things that perl
knows based on its compilation:
use Config; my $separator = $Config{path_sep};
With that, get to it. You don’t have to post your solution, but you can if you like.
You can see a list of all Challenges and my summaries as well as the programs that I created and put in the Learning Perl Challenges GitHub repository.
I’m not sure if posting solutions here is appreciated, but I hope mine is at least ok:
I don’t do much with Perl scripting that works with the shell so I had to look some stuff up. I did add the
die
line that the first poster added only because it was obvious I should have it.This solution may be a bit of overkill, but it gracefully allows for multiple arguments along with an “-a” option:
@Jack, good for you for being the first to use a platform-correct file dir separator.
@Jack: Your solution might be a bit of overkill but very instructive. 🙂
@Joel: Thank you for pointing out the platform-correct file dir separator. 🙂
I’ve changed my solution and here is the diff:
@Meir – or trimming a bit…
I wonder how comes that nobody came with a map/grep version for this. Here’s Meir’s version rewritten in such a way:
The usage line is modified from some of the previous postings.
This is my version of rhich
Well after some consideration, I think it might be best to dip back to CPAN:
In fact, its simple enough that it makes an effective one-liner