Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do make make subroutine parameter as readwrite

Tags:

raku

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?

like image 898
tejas Avatar asked Jan 04 '17 18:01

tejas


1 Answers

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
like image 86
Brad Gilbert Avatar answered Oct 17 '22 17:10

Brad Gilbert