Training, Open Source computer languages
PerlPHPPythonMySQLApache / TomcatTclRubyJavaC and C++LinuxCSS 
Search for:
Home Accessibility Courses Diary The Mouth Forum Resources Site Map About Us Contact
work on files in a directory

Posted by neni (neni), 16 June 2005
Graham Hi!

how can i open each file in a directory,  and add that file name and line number on each line (there is data on each line).


Thanks in advance


Posted by admin (Graham Ellis), 16 June 2005
Code:
opendir DH,".";
foreach $thing (readdir DH) {
       next unless (-f $thing and -r $thing);
       open (FH,$thing);
       $ln = 0;
       while (<FH>) {
               $ln++;
               print "$thing $ln: ";
               print;
               }
       }


Posted by neni (neni), 16 June 2005
Graham thanks for the reply. however, when i run the program the output has all the files merged together and i am getting a single file. i would like the output files to be separate (same as before) but want the file name and line number added to each of them. sorry if i was not clear in my first posting.


The output of this code is


file1 1: some data
file1 2: some data
file1 3: some data
file1 4: some data
file1 5: some data
file1 6: some data
file2 1: some data
file2 2: some data
file2 3: some data
file2 4: some data
file2 5: some data
and so on......

thanks



Posted by admin (Graham Ellis), 16 June 2005
You can't output directly to a file of the same name, as you'll overwrite the original before you have read it. SO ...

1. Open a file for output (with an extra extension such as .new) at the same time as you open the input file

2. Print to the new file handle rather than to stdout

3. Use the ren function to rename the new file once you've completed the writing to it.

There are exceptions, but it's generally very bad practise to include the name of a file within the file data - it makes it very hard to rename the file and still have it function as you wish, for example.  What are you doing?  

Posted by neni (neni), 16 June 2005
i want  to  merge the files in the next step and be able to track the origin of the data as there is duplicate data in these files and also wanted to keep them individually in the modified form as  back-up . After what you advised i have dropped that  idea.

thanks for the help




This page is a thread posted to the opentalk forum at www.opentalk.org.uk and archived here for reference. To jump to the archive index please follow this link.

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2012: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho