On Wednesday, November 5, 2003, at 05:20 PM, [EMAIL PROTECTED] wrote:

This is my first attempt. My misunderstanding was in the fact that I could
put the filehandles inside another filehandles while loop.

Good start. Now I'll help. ;)


#!perl

#!/usr/bin/perl


...is more standard.

use strict;

and...


use warnings;

&read_the_files;

Yuck. Don't do this. Call subs with:


sub_name();

Trust me.

While we're at it, don't stick in a sub just for the sake of a sub. If you're defining and calling it at the same place, what's the point?

sub read_the_files{
print "\nread_the_files";#
my$file1 ="./file1.txt";
#contents of file1.txt
#1;;;;
#6;;;;
my$file2 = "./file2.txt";
#contents of file2.txt
#;;;;5
#;;;;10
my$file3 = "./file3.txt";
#contents of file3.txt
#;;;4;
#;;;9;
my$file4 = "./file4.txt";
#contents of file3.txt

I believe this is a misprint and you meant #...file4.txt


#;;;;5
#;;;;10

This is identical to file2.txt. What do you do then, overwrite?


my$writing = "./combined.txt";
my$count;
unless(open(FH, $file1)){print "\nCouldn't read $file1";exit}else{print
"\nOpen successful"}


#######################
#this next bit of code seems old and sloppy.

[ snip rest of code }


You're right, sloppy. I mean that in the best possible way though. :D

Anytime you find yourself typing nearly the same lines over and over again, you're probably missing a needed loop. That's exactly what loops are for in fact, repeating code.

Here's my first crack at your problem, see what you think:

#!/usr/bin/perl

use strict;
use warnings;

my @results;

for my $file (qw(file1 file2 file3 file4)) {
        open IN, '<', "$file.txt" or die "Input error:  $!\n";
        while (<IN>) {
                $results[$. - 1] = [ ] unless $results[$. - 1];
                $results[$. - 1][length $1] = $2 if /^(;*)(\d+)/;
        }
        close IN;
}

open OUT, '>', 'combined.txt' or die "Output error:  $!\n";
{
        no warnings 'uninitialized';
        print OUT join(':', @$_), "\n" foreach @results;
}
close OUT;

Even better, in my opinion, would be to remove those hard coded files and make a UNIX filter you would call with something like:

perl filter file?.txt >combined.txt

That looks like this:

#!/usr/bin/perl

use strict;
use warnings;

my @results;

while (<>) {
        $results[$. - 1] = [ ] unless $results[$. - 1];
        $results[$. - 1][length $1] = $2 if /^(;*)(\d+)/;
        close ARGV if eof;
}

{
        no warnings 'uninitialized';
        print join(':', @$_), "\n" foreach @results;
}

Well, hopefully that at least gives you a couple of ideas. Good luck.

James


-- To unsubscribe, e-mail: [EMAIL PROTECTED] For additional commands, e-mail: [EMAIL PROTECTED]



Reply via email to