I’m having trouble modifying a script that processes files passed as command line arguments, merely for copying those files, to additionally modifying those files. The following perl script worked just fine for copying files:
use strict;
use warnings;
use File::Copy;
foreach $_ (@ARGV) {
my $orig = $_;
(my $copy = $orig) =~ s/\.js$/_extjs4\.js/;
copy($orig, $copy) or die(qq{failed to copy $orig -> $copy});
}
Now that I have files named “*_extjs4.js”, I would like to pass those into a script that similarly takes file names from the command line, and further processes the lines within those files. So far I am able get a file handle successfully as the following script and it’s output shows:
use strict;
use warnings;
foreach $_ (@ARGV) {
print "$_\n";
open(my $fh, "+>", $_) or die $!;
print $fh;
#while (my $line = <$fh>) {
# print $line;
#}
close $fh;
}
Which outputs (in part):
./filetree_extjs4.js
GLOB(0x1a457de8)
./async_submit_extjs4.js
GLOB(0x1a457de8)
What I really want to do though rather than printing a representation of the file handle, is to work with the contents of the files themselves. A start would be to print the files lines, which I’ve tried to do with the commented out code above.
But that code has no effect, the files’ lines do not get printed. What am I doing wrong? Is there a conflict between the $_ used to process command line arguments, and the one used to process file contents?
It looks like there are a couple of questions here.
What I really want to do though rather than printing a representation of the file handle, is to work with the contents of the files themselves.
The reason why
print $fhis returningGLOB(0x1a457de8)is because the scalar$fhis a filehandle and not the contents of the file itself. To access the contents of the file itself, use<$fh>. For example:will print the contents of the entire file.
This is documented in
pelrdoc perlop:But it has already been tried!
I can see that. Try it after changing the open mode to
+<.According to
perldoc perlfaq5:It goes without saying that the
or die $!after theopenis highly recommended.But take a step back.
There is a more Perlish way to back up the original file and subsequently manipulate it. In fact, it is doable via the command line itself (!) using the
-iflag:See
perldoc perlrunfor more details.I can’t fit my needs into the command-line.
If the manipulation is too much for the command-line to handle, the
Tie::Filemodule is worth a try.