#!/usr/bin/perl # # Find_File_testcase.pl [-r] [dir/file...] # # This tests and highlights how in perl Find::File traverses directories. # # It shows.. # * The order in which calls to "preprocess" and "wanted" are made. # * How you can sort the files and directories being traversed. # * But that Find:File always handles files and directories separately, all # the files first, then all the directories, though each group is in the # order in which the user sorted them. No option is provided to traverse # files and directories in the order given. # * How a 'recursion flag' can be implement, reminesient of "ls" # # See "dir_traversal_notes" for more information # use strict; use File::Find; my $PROGNAME="Find_File_testcase.pl"; my $recurse = 0; if ( @ARGV && $ARGV[0] eq '-r' ) { $recurse=1; shift; } @ARGV = ( "." ) unless @ARGV; if ( $ARGV[0] =~ /^-/ ) { print STDERR "Usage: $PROGNAME [-r] [dir|file...]\n"; exit 10; } my %find_opts = ( preprocess => \&enter_dir, # enter and sort contents of a directory postprocess => \&leave_dir, # just mark the end of a recursive step wanted => \&do_files, # process each item in directory ); my $sub_dir; while ( $_ = shift ) { $sub_dir=0; # not a sub-directory find(\%find_opts, $_ ); } exit 0; sub enter_dir { print "---> $File::Find::dir (", scalar @_, ")\n"; return ( sort @_ ); # Sort filenames. #return ( sort { $b cmp $a } @_ ); # Sort filenames in reverse order #return ( sort { $a <=> $b } @_ ); # Sort filenames numerically #return ( @_ ); # Don't Sort filenames. } sub leave_dir { print " <---: $File::Find::dir\n"; } sub do_files { # Handle Recursion # Any sub-directory seen at this point is to be pruned, # unless recursion is enabled. # Pruned sub-directories if ( -d $_ ) { $File::Find::prune = $sub_dir; $sub_dir=!$recurse; } # print "\t$_\n"; # just the name printf "\t%-4s $_\n", # name and file type -d $_ ? "DIR" : -f _ ? "FILE" : "???"; # printf "\t%-4s $File::Find::name\n", # -d $_ ? "DIR" : -f _ ? "FILE" : "???"; }