Saturday 15 February 2014

Perl - build 2D array from 2 arrays of equal length -


So I should say that I actually solved it, but the syntax is horrible so I want to see that theres There is a Pearl-iSH way to do that which is good.

I have two arrays of length ( @jenase and @names ). I want to add them to the combined values ​​of a single 2D array.

My attitude is right now;

  $ num = Number of elements in each array of my @jen = (); Foreach My $ i (0 .. $ num-1) {foreach my $ j (0 .. 1) {if ($ j == 0) {push $ {$ genes [$ i]}, $ name [$ i ];} If ($ J == 1) {push @ {$ gene [$ i]}, $ length [$ i];}}}   

but a clear line for it Need for every additional column (right now I have two - name and length) Also it is hateful code only a mother can love.

Note any ideas that

  @jinz = (\ lighthouse, \ @name);   

what

You can at least do the following:

  foreach my $ i (0 .. $ num-1) {push @genes, [$ names [$ i], $ length [$ i]]; }   

If you do not care about input arrays, you can consume them:

  push @genes, [shift @ names , Shift @lengths] while @name;   

There are also some modules which you can use to iterate on many lists. For example, using list :: MoreUtils :: each_array :

  Usage list :: MoreUtils qw (each_array); My $ is = every_are (@name, @length) while (mine ($ n, $ l) = $ it- & gt; ()) {push @genes, [$ n, $ l]; }   

With it, list :: MoreUtils :: pairwise :

  Usage list :: MoreUtils qw (pairwise) with; @jenz = partner {[our $ one, our $ B]} @name, @langries; Algorithms :: Loops Recommended using 'mappers', with   

algorithm :: loops :: mappers :

  ; @ Genus = mappakare {\ @_} \ (@name, @ langha)    

No comments:

Post a Comment