Perl: array reference versus anonymous array

后端 未结 3 1952
无人及你
无人及你 2021-01-12 06:08

This may be a silly question... The following code outputs the contents of @arrayref and @arraycont respectively. Note the difference between them

3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-12 06:53

    You made stored references to a single array in both $arrayref[0] and $arrayref[1]. You should have used different arrays.

    my @refs;
    
    my @array1 = qw(1 2 3 4);
    push @refs, \@array1;
    
    my @array2 = qw(5 6 7 8);
    push @refs, \@array2;
    

    In practice, my is executed in each pass of a loop, creating a new array each time.

    my @refs;
    while ( my @row = get() ) {
       push @refs, \@row;
    }
    

    In rare occasions where you have to clone an array, you can use:

    use Storable qw( dclone );
    
    push @refs, [ @row ];       # Shallow clone
    push @refs, dclone(\@row);  # Deep clone
    

提交回复
热议问题