Assign address of one array to another in Perl possible?

后端 未结 4 1461
深忆病人
深忆病人 2021-01-29 02:07

In the following C# code:

int[] X = new int[2];
X[0] = 1;
X[1] = 2;
int[] Y = X;
X[1] = 3;

After this executes, Y[1] will also be 3 since the o

4条回答
  •  攒了一身酷
    2021-01-29 02:44

    You're using a reference in the C# program, but not in the Perl program. It works the same if you use a reference in Perl.

    my $X = [ 1, 2 ];
    my $Y = $X;
    $X->[1] = 3;
    print "@$Y\n";  # 1 3
    

    or

    my @X = ( 1, 2 );
    my $Y = \@X;
    $X[1] = 3;
    print "@$Y\n";  # 1 3
    

    You could also create an alias.

    use Data::Alias qw( alias );
    
    my @X = ( 1, 2 );
    alias my @Y = @X;
    $X[1] = 3;
    print "@Y\n";  # 1 3
    

提交回复
热议问题