加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-15 23:30:04 所属栏目:大数据 来源:网络整理
导读:我在编写函数时遇到问题… sub TemplateReplace{ my($regex,$replacement,$text) = @_; $text =~ s/($regex)/($replacement)/gs;}my $text = "This is a test.";TemplateReplace("test","banana",$text); 但它不起作用.我认为参数是在Perl中通过引用发送的.
我在编写函数时遇到问题…

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 "$textn";

sub template_replace {
    my $regex       = shift;
    my $replacement = shift;
    $_[0] =~ s/$regex/$replacement/gs;
}

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读