Suppose I have a subroutine that swaps two given parameters. It logically needs to have read write parameters.
sub swap($l, $r)
{
my $tmp = $l;
$l=$r;
$r=$tmp;
}
I get the error:
Cannot assign to a read only variable ($l) or a value
I don't think I can try \$param
like in perl5.
I think I should try something with :=
but the documentation doesn't mention anything about the function parameters.
How do I pass parameter as a reference to this subroutine so that I can change its value?
sub swap ( $l is rw, $r is rw ) {
($r,$l) = ($l,$r)
}
my $a = 1;
my $b = 2;
swap $a, $b;
say $a; # 2;
my @a[2] = 1,2;
swap |@a;
say @a; # [2 1]
You can use reverse
as well for what you are trying to accomplish.
my $a = 1;
my $b = 2;
($a,$b) .= reverse;
say $a; # 2
say $b; # 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With