How to make make a subroutine parameter like readwrite

Suppose I have a routine that changes two given parameters. It should logically have read write parameters.

sub swap($l, $r) { my $tmp = $l; $l=$r; $r=$tmp; } 

I get an error message:

Cannot assign read-only variable ($ l) or value

I don’t think I can try \$param like in perl5.

I think I should try something with := , but the documentation says nothing about function parameters.

How do I pass a parameter as a reference to this routine so that I can change its value?

+6
source share
1 answer
 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 as what you are trying to accomplish.

 my $a = 1; my $b = 2; ($a,$b) .= reverse; say $a; # 2 say $b; # 1 
+10
source

Source: https://habr.com/ru/post/1013760/


All Articles