Lines written to a file are not contiguous. First I will describe what I want the script to perform and then I will include the script at the end of this message. I downloaded the Oreilly Programming Perl Version 4 examples. There are 30 directories with 2211 files. I want each chapter to have a consolidated file with all the examples for that chapter. I created the consolidate_examples.pl script which goes into each directory, reads each file, and then writes the files lines to the consolidated_perl4_examples/<directory name>. An example is consolidated_perl4_examples/ch00_preface with contains six lines. ch27_perl_functions is the largest and has 435 files which results in a single file with 870 lines. What I expected is as follows. If the first file I read from contains six lines then I expected the resulting consolidated file to have the first six lines align with read-from file. But they don't. The consolidated file's lines are mixed with the first six lines comming from file 1 or file 8 or whatever. The lines read in are not contiguous. For example in ch12 the first consolidated line comes from file 004 and the second consolidated line comes from 055.
------------ SCRIPT -------------- #!/usr/bin/perl use v5.16.3; # use v5.14.2; use File::Basename; use File::Path; my $base_directory = "/home/sherman/perl_documentation/programming_perl_4_examples/programming_perl_examples/program_listings"; my $basename_directory = basename($base_directory) || die "Unable to determine the basename: $!\n"; my $write_directory = "/home/sherman/perl_documentation/programming_perl_4_examples/consolidated_perl4_examples"; if ( not -e "$write_directory" ) { mkdir("$write_directory") || die "Unable to create $write_directory: $!\n"; } chdir($base_directory) || die "Unable to change directory to $basename_directory: $!\n"; opendir(PERLDIR, ".") or die "Unable to open $basename_directory: $!\n"; my @docdirs = grep { $_ ne '.' and $_ ne '..' } readdir PERLDIR; closedir(PERLDIR) || die "Unable to close $basename_directory:$!\n"; foreach my $directory ( @docdirs ) { chdir("$base_directory/$directory") || die "Unable to change directory to $directory: $!\n"; my $write_file = "$write_directory/$directory"; opendir(EXAMPLES, ".") or die "Unable to open $directory: $!\n"; my @docfiles = grep {$_ ne '.' and $_ ne '..'} readdir EXAMPLES; closedir(EXAMPLES) || die "Unable to close $directory: $!\n"; foreach my $file ( @docfiles ) { my ( $write, $read ); open(WRITE, ">>$write_file") || die "Unable to open $write_file: $!\n"; open(READ, $file) || die "Unable to open $file: $!\n"; my $line = readline(READ) || die "Unable to read $file: $!\n"; print WRITE "$line\n"; close(WRITE) || die "Unable to close $write_file: $!\n"; close(READ) || die "Unable to close $file: $!\n"; } } 1;