@H_403_1@
我在编写函数时遇到问题…
sub TemplateReplace { my($regex,$replacement,$text) = @_; $text =~ s/($regex)/($replacement)/gs; } my $text = "This is a test."; TemplateReplace("test","banana",$text);
但它不起作用.我认为参数是在Perl中通过引用发送的.这行是我的($regex,$text)= @_;然后复制它们?我该如何解决?
解决方法
您正在修改传入的$文本的副本;这对原版没有影响.
#!/usr/bin/perl use strict; use warnings; my $text = "This is a test."; template_replace(qr/test/,"bannana",$text); print "$text\n"; sub template_replace { my $regex = shift; my $replacement = shift; $_[0] =~ s/$regex/$replacement/gs; }
上面的代码是有效的,因为@_的元素是传入的变量的别名.但是Adnan的答案是更常见的.修改传递给函数的参数是令人惊讶的行为,并且使得像template_replace(qr / foo /,“bar”,“foo is foo”)这样的东西不起作用.