2

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";
      }
5
  • Just use push @{ $loc_info{$marker} }, $location; and you don't need prior test with exists. Commented Feb 1, 2016 at 20:59
  • 1
    Please post that as an answer. (I'm sorry, I can't address my comment as I can't type your name and I'm using the tablet app which provides neither auto-complete nor copy.) Commented Feb 1, 2016 at 21:04
  • 1
    @Kpangee: Whenever you use split /\s+/ you almost certainly want split ' ' (with exactly one space) or just split which is identical Commented Feb 1, 2016 at 21:09
  • Possible duplicate of How can I push an element into an array reference held as a hash value? Commented Feb 1, 2016 at 21:15
  • See also: autovivification for why you can use nonexistent data structures as if they already existed Commented Feb 1, 2016 at 21:19

1 Answer 1

4

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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

Hi Folks,thank you so much for sharing your knowledge with me. I really appreciate your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.