I am trying to use a script to replace the header of each file, whose filename are stored within the array $test, using the sed command within a Perl script as follows:
This script doesn't work as is and I think it might be something with the syntax of how to call the element of an array within a embedded sed command. If I put an actual integer as the array index instead of the variable $count, it works fine, but if I try to use $count, it doesn't work at all. I know this might not be the most efficient method, but it is the only way I can think of with my limited knowledge of perl scripting.
First, why would you use such a sed script within Perl? But whatever. Second, the second back-ticked command, while functionally correct, is not as good or as clear as:
rename(0, ${test[$count]});
Third, the last one in the array never gets converted. That's because $#test is the last index in the array of @test, and you're telling the while loop to stop before count is equal to this.
Now to your actual question. I dont know. This worked when I ran sample code and on the files (except for the last). However, better code would be as follows:
Like otheus said, why use sed in a Perl script? If you are going to use Perl, you had better learn how to use it properly. Otherwise stick with sed.
Here's a small Perl script that will do what you want and create a backup file to boot.
I called this replace.pl
#!/usr/bin/perl
use strict;
use warnings;
use English qw( -no_match_vars );
my $old;
my $new;
my $oldFH;
my $newFH;
my $dirDH;
my $dir = "."; #Use current directory
opendir($dirDH, $dir) or die "Cannot opendir $dir\n";
my @test = readdir($dirDH);
foreach $old (@test) {
next if $old eq '.'; #skip directory entries
next if $old eq '..';
$new = "$old.temp";
open($oldFH, "<", $old) or die "can't open $old: $OS_ERROR\n";
open($newFH, ">", $new) or die "can't open $new: $OS_ERROR\n";
while (<$oldFH>) {
$_ =~ s/BIOGRF 321/BIOGRF 332/g;
print $newFH $_ or die "can't write $new: $OS_ERROR\n";
}
close($oldFH) or die "can't close $old: $OS_ERROR\n";
close($newFH) or die "can't close $new: $OS_ERROR\n";
rename($old, "$old.orig") or die "can't rename $old to $old.orig: $OS_ERROR\n";
rename($new, $old) or die "can't rename $new to $old: $OS_ERROR\n";
}
closedir($dirDH) or die "Cannot closedir $dir\n";
exit 0;
The guts of the code comes from The Perl Cookbook. I just wrapped it around a loop that takes all the files from the current directory and performs your replace command. In your case you just need the while loop that walks through your array called @test.