Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

perl6 - assignment to parameter

Is there a way to do an assignment to a formal parameter?

Something like:

sub myfunc($n) {
    $n = $n + 5;
    return $n;
}

Or, would I have to create a new variable and assign the value of $n to it?

like image 847
user6189164 Avatar asked Mar 18 '18 21:03

user6189164


2 Answers

You can use the is copy trait on parameters:

sub myfunc($n is copy) {
    $n = $n + 5;
    return $n;
}

See https://docs.raku.org/type/Signature#index-entry-trait_is_copy for more information.

like image 90
Elizabeth Mattijsen Avatar answered Jan 04 '23 17:01

Elizabeth Mattijsen


As mentioned by Elizabeth Mattijsen you probably want to use is copy.

However, if you really intend to mutate a variable used as an argument to that function, you can use the is rw trait:

my $num = 3;

mutating-func($num);

say $num; # prints 8

sub mutating-func($n is rw) {
    $n = $n + 5;
    return $n;
}

But this opens you up to errors if you pass it an immutable object (like a number instead of a variable):

# dies with "Parameter '$n' expected a writable container, but got Int value"
say mutating-func(5); # Error since you can't change a value

sub mutating-func($n is rw) {
    $n = $n + 5;
    return $n;
}
like image 20
Christopher Bottoms Avatar answered Jan 04 '23 16:01

Christopher Bottoms