It looks like you've confused what you can do from the command line with some run options and what you need to do within a larger program contained in a file. You can't just take something that would go with perl -i~ -ne as an argument on the command line and use it as a statement in a standalone program.
You can, if you really want, use system to call perl from within a Perl program. A filter program may be in order to use with your shell's redirection. However, what you really should do if you want to make this maintainable and all in one program is learn to open your file, check for errors on the system call, read the lines, do the substitution, close the file, and check for errors on that system call, too.
The best way to do all of that isn't to edit it in place, but to write to a new file and optionally overwrite the old file. Many people do this in the order of reading the existing file, writing the changes to a new file, then renaming the new file over the old one. I prefer to rename the old file, read the original data from the renamed file, write to a new file by the old name, then delete (if desired) the renamed file after successfully closing the new one.
It goes a little something like this:
#!/usr/bin/perl
use strict;
use warnings;
use Date::Format;
my $delete_temp = 0;
# deleting the temp probably should be a command-line option
my $old = 'filename.html';
my $tmp = $old . '.bak';
my $date = (time2str ("%Y-%m-%d", time));
print "\n\n$date\n\n";
rename $old, $tmp or die "Cannot rename $old to $tmp: $!\n";
open my $in, '<', $tmp or die "Cannot read $tmp: $!\n";
open my $out, '>', $old or die "Cannot write to $old: $!\n";
while ( <$in> ) {
s!(\d\d\d\d-\d\d-\d\d)(-[a-z_]{5,30}\.zip)!$date$2!g;
# no backslash before the sigil on $date
print $out $_;
}
close $out or die "Error writing to $old: $!\n";
close $in;
if ( $delete_temp ) {
unlink $tmp or die "Error removing $tmp: $!\n";
}
The backslash you have in your substitution means to replace the date with the literal string '$date' and then the contents of the variable $2. I took it out of my example and put in a comment there. What you really want is the contents of the variable, not its name.
The deletion of the temp file, as stated in the comment for its controlling variable, would be better off as a command-line argument to your program. Some Getopt module is the usual suggested way to do that. Using those modules or rolling an argument parser is either one beyond the scope of this node.
I'd recommend getting a good book on Perl like Effective Perl Programming, Programming Perl, or Learning Perl. Maybe you prefer one of the free books available online (or all of them, since they're free) like Beginning Perl, Learning Perl the Hard Way, or Extreme Perl. |