Minimal Perl for Unix and Linux People: Part 2 | WebReference

Minimal Perl for Unix and Linux People: Part 2

[previous] [next]

Perl as a (Better) Find Command: Part 2

By: Tim Maher

6.4 Processing Filename Arguments

Have you ever run the grep command, only to find yourself suddenly staring at a screen full of blinking graphics characters? Most Unix users should witness this phenomenon sooner or later, because it's not only the closest approximation to the Aurora Borealis you'll ever see on a computer terminal, it's also a rite of passage for Unix newbies.

If you don't know what I'm talking about, feast your eyes on figure 6.1, which shows what happened when a hapless user attempted to search all files under $HOME for lines containing the letter e, using POSIX grep.

Unfortunately for that user, grep doesn't treat $HOME as some kind of magical reference to all the files within the director y it names, as many are prone to assume. Instead, it's taken as the name of the specific file that's to be opened and examined for matches! As luck would have it, this directory file did contain some occurrences of the letter e, so grep dutifully sent the associated "lines" to the screen.

But the terminal interpreted something in that data stream as a request to switch character sets, which is why it's difficult to decipher the output of the who and ls-l commands that came next.

By the way, if you're thinking, "I'm too smart too fall into that trap," consider the related commands shown here, which are just as dangerous in cases where "*" finds a subdirectory it can match:

It's scary to contemplate, but I know from my decades in Unix IT circles that many users issue commands like these all the time; they're just lucky to rarely find matches in the binary files they're inadvertently searching.

Okay, now you understand the problem, and you've seen that it's an easy trap to fall into. So you're probably asking yourself, "Is there any hope of defending the hordes of accident-prone Unix users from these grepological calamities? And what does this have to do with Perl?"

Of course there's hope; and, as usual, our salvation is achieved by Perl coming to the rescue.

Figure 6.1