One way to do this is open both the input and output file handles and pass them both to the sorting routing. Your code used a bare word name, FILE for the output file. It is not so obvious that FILE is actually changing as the program runs. Better to use a lexical file handle and pass it to sorting(). FILE is global in scope and you were using that to pass a variable to sorting(), which is not a good idea.
I prefer to close() the filehandles at the same level of code as the open().
I do have some issues with the variable names. These names are important. For the "counter", perhaps $file_num, $file_counter, $filecnt or some such. "$index_file" is confusing. First of all this is not any kind of an "index". Anyway, I suggest you spend a bit more time considering names.
Unless the for (or foreach) loop is really short and obvious, I prefer to declare an actual name for the loop variable rather than using $_; When you into the body of the loop, $_ is so generic that it can be confusing about what that really is. An extra "my variable" is a "cheap" thing to create and usually well work the effort.
Update: I went ahead and added a few lines to make this a complete program that I could test. Glob is a bit easier than readdir for a very simple case like this. You also had a number of lines of code where I couldn't figure out what the intent was, so I deleted them.
#!/usr/bin/perl use strict; use warnings; if (!-d "sorted") { mkdir "sorted" or die "unable to create dir sorted $!"; } my @files2sort = <file*.txt>; #just use glob to get names my $curfilenum =1; foreach my $file (@files2sort) { open my $fh_in, '<', $file or die "$file failed to open $!"; open(my $fh_out, '>', "./sorted/$file.sort") or die "cannot create +out $file.sort $!"; print "Processing ".$curfilenum++." of ".@files2sort." $file\n"; sortfile($fh_in, $fh_out); close ($fh_out); close ($fh_in); print "OK: Sorted $file \n"; } sub sortfile { my ($fh_in, $fh_out) = @_; my @lines = <$fh_in>; my @sorted = map { $_->[0] } sort { $a->[1] <=> $b->[1] } map { my ($x) = $_ =~ /VerNumber:\((\d+)/i; [$_, $x]; +} @lines; print $fh_out @sorted; } __END__ Processing 1 of 2 file1.txt OK: Sorted file1.txt Processing 2 of 2 file2.txt OK: Sorted file2.txt #these names are confusing... my $files_size = $#files + 1; my $index_file = 1; #better names?: my $num_files = @files; # the value of an array in a scalar context is the # number of items in the array, no need for $#files+1 # or you can just use @files in a scalar context without # creatng $num_files at all. my $file_counter =1; # "$index_file" would mean something different
In reply to Re: Use Schwartzian transform across multiple files
by Marshall
in thread Use Schwartzian transform across multiple files
by Sonya777
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |