Kpangee
Kpangee

Reputation: 57

Perl: How to push elements in array as hash value using if exists statement

I'm working with markers having multiple chromosome locations. For each marker, I'd like to get all the chromosome locations such as:

 marker_1 1A, 3B, 5D; marker_2 2D, 2A 

I'm coming from Ruby world and I've been scratching my head with reference/dereference of array and hash.I'm getting more and more confused. Could you please help me out? Thank you in advance for your time and your helpful assistance.

My code below works. However, instead of concatenating $location to an existing 'string' location, I'd like to push $location in an array. I'm not sure how to do that.

my %loc_info;

while(<IN>){
    my @info = split(/\s+/);
    my $marker = $info[1];
    my $location = $info[2];

    if (exists $loc_info{$marker}){
        $loc_info{$marker} .= ",$location";## help for pushing in array
    }else{
        $loc_info{$marker} = $location; ##
    }
}#while

     foreach (sort keys %loc_info){
         print "$_\t $loc_info{$_}\n";
      }

Upvotes: 2

Views: 1467

Answers (1)

Borodin
Borodin

Reputation: 126722

As has been mentioned, Perl's autovivication will allow you to push to a non-existent hash element. An anonymous array will be created for you

I would write this

while ( <IN> ) {
    my @info = split;
    my ($marker, $location) = @info[1,2];
    push @{ $loc_info{$marker} }, $location;
}

for my $mk ( sort keys %loc_info ) {
    my $locs = $loc_info{$mk};
    print $mk, "\t", join('; ', @$locs), "\n";
}

Upvotes: 4

Related Questions