Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't my Perl function work?

I am having trouble with a function I wrote...

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

my $text = "This is a test.";
TemplateReplace("test", "banana", $text);

But it doesn't work. I thought arguments were sent by reference in Perl. Does the line my($regex, $replacement, $text) = @_; then copy them? How do I fix this?

like image 931
rlbond Avatar asked Nov 30 '22 07:11

rlbond


1 Answers

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

 my $text = "This is a test.";
 $text = TemplateReplace("test", "banana", $text);

There. That should work.

And yes, your my( ..) = @_ does copy the args. So if you're modifying a variable, you need to return it unless it's a global.

like image 120
Adnan Avatar answered Dec 06 '22 09:12

Adnan