Re: Perl - pass by reference v pass by value

Johan Vromans <[email protected]>
Newsgroups gmane.music.equipment.slimdevices.devel
Organization Squirrel Consultancy
Message-ID <[email protected]>
On Tue, 21 Sep 2021 09:09:46 +0000, Paul Webster
<Paul.Webster.a8bjuo-NUepA2SMhDQqspMVqqL2D+4xXEVPTSb/[email protected]> wrote:

> I did not expect that the values in $variable1 to change through me
> changing a new local variable $newvalue.

That is because my is not necessarily introducing a local variable. When
used in an iteration

   foreach my $var ( $x ) {
       # $var is an alias to $x

$var becomes an _alias_ to the value referenced. If you modify it, you
modify the original. 

If you don't want that, the correct syntax is

    foreach ( ... ) {
        my $var = $_;           # now the value is copied

HTH,
	Johan
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.