in reply to Transferring hash keys to array... Need help sorting

You've been given good solutions to your problem, but I have the impression it might be the wrong problem.

See http://www.perlmonks.org/?node=xy+problem

Why do you want to have two arrays in sync? You probably want this because you don't know how to do something that could be done another easier way, so you come up with this question.

May be you should explain what you're really trying to do, tell us about the bigger problem at a higher level, it is quite likely there is a better way to do it.

  • Comment on Re: Transferring hash keys to array... Need help sorting

Replies are listed 'Best First'.
Re^2: Transferring hash keys to array... Need help sorting
by DARK SCIENTIST (Novice) on Apr 21, 2017 at 17:11 UTC
    The reason I want array positions between the two arrays to be synced is because if I print label[0] and content[0] I want the label for a protein sequence to match the actual protein sequence itself

      In that case, you might find the concept of structured data useful.

      my $data = { key1 => { label => "label1", content => [...] }, key2 => ..., };
      The above's a HoH, i.e. hash of hashes. Start reading with perldsc perhaps.

        I actually have a hash set up already that contains keys= the labels and values= sequence content. I read these keys and values into an array because it was easier to manipulate them (reverse and tr them and insert spaces between characters). Is there a way to just manipulate them straight from a hash reference instead of putting the keys and values into arrays? If so, I can just avoid arrays all together
      It's usually easier to use $labels[0] and $hash{$labels[0]} instead of maintaining the same order in the content array. I think that's what Laurent is getting at. But if you really want to have a bunch of parallel arrays, here's the pattern for sorting them:
      my @order = sort { $labels[$a] cmp $labels[$b] } 0 .. $#labels; @labels = @labels[@order]; @content = @content[@order]; @more_content = @more_content[@order];
        Yes, that was what I was getting at. Either this, or a hash or hashes, as shown by an anonymous monk just below.