Perl To Recursive Directories And List Out Files

How do we use perl to list out all the files in a directory and subdirectories?

Answer:

Here is a routine that'll recurse a given directory (perl script.pl /path/to/search/).

Code:

#!/usr/bin/perl -w

use strict;

sub recurse($) {
  my($path) = @_;

  ## append a trailing / if it's not there
  $path .= '/' if($path !~ /\/$/);

  ## print the directory being searched
  print $path,"\n";

  ## loop through the files contained in the directory
  for my $eachFile (glob($path.'*')) {

    ## if the file is a directory
    if( -d $eachFile) {
      ## pass the directory to the routine ( recursion )
      recurse($eachFile);
    } else {

      ## print the file ... tabbed for readability
      print "\t",$eachFile,"\n";
    }
  }
}

## initial call ... $ARGV[0] is the first command line argument
recurse($ARGV[0]);
 

Note:

What does my($path) = @_; do?

@_ is a special variable that holds the arguments of a subroutine. 

This is why you don't see this in perl: sub newSubroutine($arg1,$arg2);

Instead you can do the following:

Code:

#!/usr/bin/perl -w

use strict;

sub newSubroutine {
  for my $eachArg (@_) {
    print $eachArg,"\n";
  }
}

newSubroutine('some','random','number','of','arguments');

So it's very similar to $_ only it's used with lists.

Have a Linux Problem
Linux Forum - Do you have a Linux Question?

Linux Books
Linux Certification, System Administration, Programming, Networking Books

Linux Home: Linux System Administration Hints and Tips

(c) www.gotothings.com All material on this site is Copyright.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
All product names are trademarks of their respective companies.
The site www.gotothings.com is in no way affiliated with or endorsed by any company listed at this site.
Any unauthorised copying or mirroring is prohibited.