Monday, December 3, 2007

HowTo: Translate Find Statements to Perl Codes

We have been covering up find command line statements for a while. Now here's a quick entry on how to convert find command line statements into its equivalent and executable perl codes.

Find2perl is a little translator to convert find command lines to equivalent Perl code. The resulting code is typically faster than running find itself. Find2Perl is part of perl package, which is installed by default perl installation.

In shorter words, find2perl translate find command lines to its Perl code.

Find2Perl follows the below command line format

find2perl [path] [switches] [output-perl-file]

Here are several find2perl command usage.

~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# find2perl /tmp -name "*.JPG" > sample.pl
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Make the equivalent perl code executable by root like so
# chmod 700 sample.pl

View the generated perl codes equivalent to recently issued find command
# cat sample.pl
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#! /usr/bin/perl -w
eval 'exec /usr/bin/perl -S $0 ${1+"$@"}'
if 0; #$running_under_some_shell

use strict;
use File::Find ();

# Set the variable $File::Find::dont_use_nlink if you're using AFS,
# since AFS cheats.

# for the convenience of &wanted calls, including -eval statements:
use vars qw/*name *dir *prune/;
*name = *File::Find::name;
*dir = *File::Find::dir;
*prune = *File::Find::prune;

sub wanted;

# Traverse desired filesystems
File::Find::find({wanted => \&wanted}, '/tmp');
exit;

sub wanted {
/^.*\.JPG\z/s
&& print("$name\n");
}
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

More find2perl examples
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# find2perl /tmp -name "*.jpg" -depth -print -ls > sample2.pl
# find2perl /tmp -name "*.JPG" -depth -atime -2 -print > > sample3.pl
# find2perl /tmp -iname "*.JPG" -type f -depth -atime -2 -print > sample4.pl
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

Works perly codes!

0 comments:

Sign up for PayPal and start accepting credit card payments instantly.
ILoveTux - howtos and news | About | Contact | TOS | Policy