perl6 - assignment to parameter
Asked Answered
M

2

8

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?

Mutation answered 18/3, 2018 at 21:38 Comment(0)
P
8

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.

Plunk answered 18/3, 2018 at 22:20 Comment(0)
P
3

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;
}
Promise answered 26/3, 2018 at 12:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.