Section B.26. Converting find Command Lines to Perl


B.26. Converting find Command Lines to Perl

A common task for a system administrator is to recursively search the directory tree for certain items. On Unix, this is typically done with the find command. We can do that directly from Perl, too.

The find2perl command, which comes with Perl, takes the same arguments that find does. Instead of finding the requested items, however, the output of find2perl is a Perl program that finds them. Since it's a program, you can edit it for your own needs. (The program is written in a somewhat odd style.)

One useful argument that's available in find2perl but not in the standard find is the -eval option. This says that what follows it is Perl code to be run each time that a file is found. When it's run, the current directory will be the directory in which an item is found, and $_ will contain the item's name.

Here's an example of how you might use find2perl. Suppose that you're a system administrator on a Unix machine, and you want to find and remove all of the old files in the /tmp directory.[*] Here's the command that writes the program to do that:

[*] This is a task typically done by a cron job at some early-morning hour each day.

     $ find2perl /tmp -atime +14 -eval unlink >Perl-program 

That command says to search in /tmp (and recursively in subdirectories) for items whose atime (last access time) is at least 14 days ago. For each item, the program should run the Perl code unlink, which will use $_ by default as the name of a file to remove. The output (redirected to go into the file Perl-program) is the program that does all of this. Now you merely need to arrange for it to be run as needed.



Learning Perl
Learning Perl, 5th Edition
ISBN: 0596520107
EAN: 2147483647
Year: 2003
Pages: 232

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net