繁体   English   中英

这个Perl替换有什么问题?

[英]What's wrong with this Perl replacement?

使用下面的代码,我想最后删除.log 我似乎按照perlrequick做的一切正确。 我在哪里弄糟?

test.pl

my $file = "ooout.log";
print $file."\n";
my $file =~ s/\.log//g;
print $file."\n";

输出

$ perl test.pl
ooout.log

$

您要重新声明my $file -删除my前缀以解决此问题。 如果您使用以下命令启动脚本,则会被捕获

use strict;
use warnings;

您会看到:

"my" variable $file masks earlier declaration in same scope at

其他人指出你的问题与my

我想指出您的替代代码与您的规范不完全匹配。 它将从文件名中删除所有出现的字符串.log

如果只想删除字符串结尾的.log ,请不要使用g修饰符,而应使用字符串结尾锚$

use strict;
use warnings;

my $file = "ooout.logical.log";
print "$file\n";
$file =~ s/\.log$//;
print "$file\n";

__END__

ooout.logical.log
ooout.logical

尝试从替换行中删除my

$file =~ s/\.log//g;

似乎您正在重新初始化$file

删除第二个my ,然后它将起作用。

my (有些简化)声明了一个变量。 您两次声明$file ,因此第二个my make perl会忘记第一个中的值。

您在第三行说“ my $ file”,因此您要定义另一个变量。

尝试:

my $file = "ooout.log";
print $file."\n";
$file =~ s/\.log//g;
print $file."\n";

第二个my

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM