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?
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?
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.
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;
}
© 2022 - 2024 — McMap. All rights reserved.