简体   繁体   中英

Array of references in Perl

I've read the reference documentation, but I can't figure out how to dereference the array references inside my array. Don't understand why @{$HoA{$cols[0]}} prints only the length of the array either. Any clarification is much appreciated.

file.txt :

    aa      bb
    bb      cc

The program:

#!/usr/bin/perl
use strict;
use warnings;
use Data::Dumper;

# my $filename = "file.txt";
my @newarray;

my %HoA = (
        aa        => [ "GAT_1", "GAT_2", "GAT_3", "GAT_4" ],
        bb        => [ "GAT_6", "GAT_1", "GAT_5", "GAT_4", "GAT_2" ],
        cc        => [ "GAT_6", "GAT_4", "GAT_3", "GAT_1", "GAT_2" ],
      );

open (FILE, '<' ,"$filename") or print "$filename does not exist\n";


while (<FILE>) {
    my @cols = split;
    $cols[0] = $HoA{ $cols[0] };
    #$cols[0] = @{$HoA{ $cols[0]} };
    $cols[1] = $HoA{ $cols[1] };
    #$cols[1] = @{$HoA{ $cols[1] }};
    push ( @newarray, join( " ", @cols ));
}

close FILE;

print Dumper(\@newarray);

This is my expected output:

$VAR1 = [
          [
            [
              'GAT_1',
              'GAT_2',
              'GAT_3',
              'GAT_4'
            ],
            [
              'GAT_6',
              'GAT_1',
              'GAT_5',
              'GAT_4',
              'GAT_2'
            ],
        [
              'GAT_6',
              'GAT_1',
              'GAT_5',
              'GAT_4',
              'GAT_2'   
            ],
            [
              'GAT_6',
              'GAT_4',
              'GAT_3',
              'GAT_1',
              'GAT_2'
            ],

          ]
        ];

This is my actual output:

$VAR1 = [
          'ARRAY(0x7f80110060e8) ARRAY(0x7f801102eb58)',
          'ARRAY(0x7f801102eb58) ARRAY(0x7f801102f308)'
        ];

The big problem is this line:

    push ( @newarray, join( " ", @cols ));

join is inherently a string operation: @cols is an array of references, which join then dutifully stringifies so that it can join them with " " .

It seems like what you really want is probably this:

    push ( @newarray, [@cols] );

where the [ ... ] notation creates a new anonymous array (in this case populated with the values in @cols ) and returns a reference to to it.

Additionally, instead of this:

    $cols[0] = $HoA{ $cols[0] };

(which causes @newarray and %HoA to end up containing references to the same underlying arrays), you may want this:

    $cols[0] = [ @{$HoA{ $cols[0] }} ];

(such that @newarray ends up with completely independent arrays that simply start out with the same data as what's in %HoA ). This depends on whether you're planning to modify any of the arrays afterward.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM