Learning Perl Challenge: rhich

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.

Student Workbook for Learning Perl, 2nd Edition

The Student Workbook for Learning Perl, 2nd Edition is now available for $3.99 for the DRM-free digital version, in either mobi, ePub, or PDF formats.

I wrote the first edition in 2005 as a collection of extra exercises and detailed solutions for each of the chapters in Learning Perl, then the third edition. Since 2005, we’ve released three more editions of Learning Perl. While the exercises and answers I wrote in 2005 are still good, there is new content and new features that need new exercises, including:

  • Smart matching and given-when
  • Interacting with CPAN
  • Perl 5.10+ new features

So far, this is going to be a digital-only offering, although if you’d really like a paper version, let O’Reilly know what you’d like to buy. As with any business, O’Reilly would like to offer the book in any way that will be profitable.