Hi,

I wrote the simple script to process all text files in a directory using opendir and readdir. I want to know what are alternatives for this task and what would you do differently (better).

#! /usr/bin/perl -w #test file to learn how to process multiple files at once use strict; use warnings; use Cwd; #module to get the current working directory #first get the path for current directory my $dir = getcwd; #declare the filehandeles outside the foreach loop my $text_file_fh_in; my $text_file_fh_out; #open and read only the .txt files opendir (DIR, $dir) or die $!; my @textFiles = grep /\.txt/, readdir DIR; #open each file for further processing foreach my $text_file (@textFiles) { open ($text_file_fh_in, "<", $text_file) || die "$!"; #open for r +eading #create the names of the new files my $text_file_out = $text_file; $text_file_out =~ s/\.txt//; $text_file_out = $text_file_out . '_new.txt'; open ($text_file_fh_out, ">", $text_file_out) || die "$!"; #open +for writing #tests to see if it works #print "$text_file\n"; print "$text_file_fh_in\n"; #print "$text_file_out\n"; print "$text_file_fh_out\n"; MAIN: { while (<$text_file_fh_in>){ chomp; if (/^(.*?)\.(.*?)\ (.*?)\.(.*?)\ (.*?)$/){ print $text_file_fh_out "$1\t$2\t$4\t$5\n";} } } #close the filehandles close $text_file_fh_in || die "Could not close $text_file_fh_in"; + close $text_file_fh_out || die "Could not close $text_file_fh_out" +; } closedir DIR || die "Could not close DIR";

UPDATE: Thank you for your replies.


In reply to Processing multiple files by mocnii

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.