Reading input from files and directories in the command line arguments (like grep -R).

A

Adam

A fairly normal thing to do in Perl is to read input from the files
named in the command arguments and process line by line.
while (<>) { process($_) ; }

But I want to recurse down directories the way grep -R works. So far
I've come up with this:

while (@ARGV>0) {
$filename = shift(@ARGV);
print ($filename);

if ( -d $filename ) {
@list = `ls $filename` ;
@list1 = map {chomp; $_ = $filename . "/" . $_ } @list ;
unshift(@ARGV, @list1) ;
}

elsif ( -e $filename ) {
open(INPUTFILE, $filename) ;
while($line = <INPUTFILE>) {
process($line) ;
}
close(INPUTFILE) ;
}
}


It works but I can't believe it's the best way to do it. Any better
suggestions?
 
P

Paul Lalli

A fairly normal thing to do in Perl is to read input from the files
named in the command arguments and process line by line.
while (<>) { process($_) ; }

But I want to recurse down directories the way grep -R works. So far
I've come up with this:

while (@ARGV>0) {
$filename = shift(@ARGV);
print ($filename);

if ( -d $filename ) {
@list = `ls $filename` ;
@list1 = map {chomp; $_ = $filename . "/" . $_ } @list ;
unshift(@ARGV, @list1) ;
}

elsif ( -e $filename ) {
open(INPUTFILE, $filename) ;
while($line = <INPUTFILE>) {
process($line) ;
}
close(INPUTFILE) ;
}
}


It works but I can't believe it's the best way to do it. Any better
suggestions?

Use the standard File::Find module:

#!/usr/bin/perl
use strict;
use warnings;
use File::Find;

sub wanted {
if (-f){
open INPUT, $_ or die "Cannot open $File::Find::name: $!";
while (<INPUT>){
# process $_;
}
close INPUT;
}
}

find(\&wanted, @ARGV);
__END__

read `perldoc File::Find` for more info

Paul Lalli
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,534
Members
45,008
Latest member
Rahul737

Latest Threads

Top