Link to home
Start Free TrialLog in
Avatar of cntech
cntechFlag for United States of America

asked on

Perl Program listing files in a directory

I'm a beginner at creating perl programs.  How can I create a program that will list files in a directory and provide a user with 3 command line options.  They should be able to specify a directory, which I think you use the -d option, also they can display a long listing of the files, I think you use the -l and allow them select no options.  Also, when the files are listed they should be sorted by the filename.  I'm new to creating perl programs, not sure how to accomplish this.
Avatar of Tintin
Tintin

Your specification is unclear.

You say there should be three command line options, but you have listed just 2.  What behaviour do you want when no options are selected?
There are several implementations of such a program at the following link:

http://www.nntp.perl.org/group/perl.beginners/2007/06/msg92313.html
I'll include the program here just in case the other site isn't reachable sometime in the future.

Please note: The code is (c) John W. Krahn.
#!/usr/bin/perl
use warnings;
use strict;
use Getopt::Std;
 
getopt 'hl', \my %opt;
 
exists $opt{ h } && die <<HELP;
usage: $0 [-h] [-l] [directory]
      -h    this message
      -l    long listing
HELP
 
my $dir    = shift || '.';
my $format = "%-25s %10s %-8s %-8s\n";
 
opendir my $dh, $dir or die "Cannot open '$dir' $!";
 
if ( exists $opt{ l } ) {
     printf $format, 'File Name', 'Size', 'Owner', 'Group'
     }
else {
     print "File Name\n"
     }
 
while ( my $file = readdir $dh ) {
     my ( $uid, $gid, $size ) = ( lstat "$dir/$file" )[ 4, 5, 7 ] or die 
"Cannot stat '$dir' $!";
     next unless -f _;
     if ( exists $opt{ l } ) {
         printf $format, $file, $size, scalar getpwuid $uid, scalar 
getgrgid $gid
         }
     else {
         print "$file\n"
         }
     }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of agriesser
agriesser
Flag of Austria image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial