#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    1
    Rep Power
    0

    List files in a directory into array and print


    I would like to list all *.rpt files in a directory into an array and then convert each file name into a link. The $rpts parameter is sourced from an html page with three links: Billing, GL, Inventory. I have presented test code here for review. When you replace $rpts with, say, 'billing', one would expect a list of files to display but nothing happens -?! Any help would be greatly appreciated!


    #!/usr/bin/perl

    #use strict;
    use CGI qw(:standard);

    #Three types of web reports: Billing, GL, Inventory
    #my $rpts = param('reports');

    my $dir = "/production/reports/$rpts";

    opendir(DIR, $dir);

    while (my @file = readdir(DIR)) {

    # We only want files
    next unless (-f "$dir/@file");

    # Use a regular expression to find files ending in .rpt
    next unless (@file =~ m/\.rpt$/);

    print "$file(@file)\n";
    }

    closedir(DIR);

    exit 0;
  2. #2
  3. Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Apr 2012
    Location
    spaceBAR Central
    Posts
    229
    Rep Power
    42
    Try it like this:
    Code:
    my $file_name_search  =  "dir_path/*.rpt";
    my @file_names_found;
    
    # Search for files and load array of qualified file names to zip.
    @file_names_found  =  glob("$file_name_search");
    
    # Print names of files found
    if ( ! @file_names_found ) {
      print "No files were found.\n";
    } else {
      foreach $fnf ( @file_names_found ) {
        print "$fnf\n";
      }
    }
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Jun 2012
    Posts
    837
    Rep Power
    496
    Originally Posted by machina

    #!/usr/bin/perl

    #use strict;
    use CGI qw(:standard);

    #Three types of web reports: Billing, GL, Inventory
    #my $rpts = param('reports');

    my $dir = "/production/reports/$rpts";
    # ...
    This would not compile if you had uses the "use strict;" and "use wartnings;" pragmas because the $repts variable is not defined.

    Code:
    print "$file(@file)\n";
    also does not make much sense to me.

    You could try this:

    Perl Code:
    my @file_list = glob ("/production/reports/*.rpt");
    @file_list = grep {-f $_} @file_list;
    print "@file_list", "\n";
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Intermediate (1500 - 1999 posts)

    Join Date
    Apr 2009
    Posts
    1,941
    Rep Power
    1225
    Rather than using 2 (or more) statements to get the file list, I'd use a single grep statement.

    Code:
    my $search_pattern   = '/production/reports/*.rpt';
    my @file_list        = grep { -f } <$search_pattern>;

IMN logo majestic logo threadwatch logo seochat tools logo