Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 819
  • Last Modified:

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.
0
cntech
Asked:
cntech
  • 3
1 Solution
 
TintinCommented:
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?
0
 
agriesserCommented:
There are several implementations of such a program at the following link:

http://www.nntp.perl.org/group/perl.beginners/2007/06/msg92313.html
0
 
agriesserCommented:
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

0
 
agriesserCommented:
Did this script work for you?
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now