What's wrong with this Perl replacement?
Using the code below, I want to remove the .log
at the end. I seem to be doing everything right according to perlrequick. Where did I mess up?
test.pl
my $file = "ooout.log";
print $file."\n";
my $file =~ s/\.log//g;
print开发者_运维知识库 $file."\n";
output
$ perl test.pl
ooout.log
$
You're redeclaring my $file
-- remove the my
prefix to fix this. This would be caught if you started your script with
use strict;
use warnings;
You would have seen:
"my" variable $file masks earlier declaration in same scope at
Others have pointed out your problem with my
.
I'd like to note that your substitution code does not exactly match your spec.
It will delete all occurrences of the string .log
from your file name.
If you only want to delete .log
at the end of your string, don't use the g
modifier, and do use the end-of-string anchor $
:
use strict;
use warnings;
my $file = "ooout.logical.log";
print "$file\n";
$file =~ s/\.log$//;
print "$file\n";
__END__
ooout.logical.log
ooout.logical
Try removing my
from the replace-line:
$file =~ s/\.log//g;
It seems like you are reinitializing $file
.
Remove the second my
, then it will work.
my
(somewhat simplified) declares a new variable. You are declaring $file
twice, so the second my
makes perl forget the value in the first one.
You're saying "my $file" in the third line, so you're defining another variable.
Try:
my $file = "ooout.log";
print $file."\n";
$file =~ s/\.log//g;
print $file."\n";
The second my
.
精彩评论