为什么我的Perl功能不起作用?

rlb*_*ond 4 perl function pass-by-reference

我在编写函数时遇到问题...

sub TemplateReplace
{
    my($regex, $replacement, $text) = @_;
    $text =~ s/($regex)/($replacement)/gs;
}

my $text = "This is a test.";
TemplateReplace("test", "banana", $text);
Run Code Online (Sandbox Code Playgroud)

但它不起作用.我认为参数是在Perl中通过引用发送的.my($regex, $replacement, $text) = @_;然后该行复制它们吗?我该如何解决?

Adn*_*nan 10

sub TemplateReplace
{
   my($regex, $replacement, $text) = @_;
   $text =~ s/($regex)/($replacement)/gs;
   return $text;
}

 my $text = "This is a test.";
 $text = TemplateReplace("test", "banana", $text);
Run Code Online (Sandbox Code Playgroud)

那里.这应该工作.

是的,你的我的(..)= @_确实复制了args.因此,如果您正在修改变量,则需要将其返回,除非它是全局变量.


Cha*_*ens 8

您正在修改$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;
}
Run Code Online (Sandbox Code Playgroud)

上面的代码是有效的,因为@_的元素是传入的变量的别名.但Adnan的回答是更常见的.修改传递给函数的参数是令人惊讶的行为,并使事情变得template_replace(qr/foo/, "bar", "foo is foo")不起作用.