CGI/Perl Guide | Learning Center | Forums | Advertise | Login
Site Search: in

  Main Index MAIN
INDEX
Search Posts SEARCH
POSTS
Who's Online WHO'S
ONLINE
Log in LOG
IN

Home: Perl Programming Help: Beginner:
modifying a program to open all files in a directory

 



oldrob
Novice

Mar 13, 2013, 5:17 PM

Post #1 of 3 (262 views)
modifying a program to open all files in a directory Can't Post

Hello Perl Gurus,

I have written a script to take input files, copy specific data and output a combined file (see code below). Id like to make it so that I just have to specify a directory on the command line so that the script will automatically work on all the contained files - any help much appreciated!


Code
 
#a program to parse flow data
#!/usr/bin/perl
use warnings;
my @buffer;
my @data;

foreach (@ARGV) {
$filename = $_; #sets the filename variable
open (my $fh, '<',$filename);
$lineno = 1;
while (<$fh>) {
$lineno++;
if ($lineno == 3) {
chomp(@buffer = <$fh>); #copy the entire line to @buffer
unshift(@buffer, "$filename \t"); #add the filename before the string
push (@buffer, "\n"); #add a newline after the string
push (@data, @buffer);
}

}
}

open OUTPUT, '>', "output.txt";
print OUTPUT "@data";



Chris Charley
User

Mar 13, 2013, 5:54 PM

Post #2 of 3 (258 views)
Re: [oldrob] modifying a program to open all files in a directory [In reply to] Can't Post


Code
chomp(@buffer = <$fh>); #copy the entire line to @buffer

This doesn't copy line 3 to @buffer. It copies lines 3 to eof to the buffer.

Update: Ok, I guess thats what you want the program to do - sorry.

You can use the glob function to get files like below.

Code
my $dir = shift @ARGV; 
my @cvs_files = glob "$dir/*.csv";

You would just need to specify your directory on the command line immediately after the program, like perl my_program.pl dir_name


(This post was edited by Chris Charley on Mar 14, 2013, 8:59 AM)


oldrob
Novice

Mar 14, 2013, 3:01 PM

Post #3 of 3 (236 views)
Re: [Chris Charley] modifying a program to open all files in a directory [In reply to] Can't Post

Many thanks Chris, this did the trick nicely!

 
 


Search for (options) Powered by Gossamer Forum v.1.2.0

Web Applications & Managed Hosting Powered by Gossamer Threads
Visit our Mailing List Archives