Good day. There are two arrays that I get by querying the database. The first

my $dbquery1 = $db->selectall_arrayref("select * from DPTDAT where ID = 1"); foreach my $rowMPT_DAT1 (@$dbquery1) { my ($f1, $f2, $f3,$f4,$f5,$f6,$f7,$f8,$f9,$f10,$f11,$f12,$f13,$f14) = @$rowMPT_DAT1; } 

Second

  my $dbquery2 = $db->selectall_arrayref("select * from DPTDAT where ID = 2"); foreach my $rowMPT_DAT2 (@$dbquery2) { my ($ff1, $ff2,$ff3,$ff4,$ff5,$ff6,$ff7,$ff8,$ff9,$ff10,$ff11,$ff12,$ff13,$ff14)=@$rowMPT_DAT2;} 

I need to add, for example, each $f11 and $ff11 Tell $ff11 how to do it better?

  • Better to let the base do it for you. But in general, who prevents to make a normal cycle? - KoVadim
  • I also need to change the contents of $ f11 and $ ff11 there are not prime numbers, with them it will not be possible to immediately produce a mat. operations. And about the cycle, I can just make two requests in a loop and already perform operations inside? - Evgeniy A
  • 2
    two requests can be done if neat. There is one feature in your code - it can produce different results. The fact is that if the sort order is not specified in select, the data can be given in an arbitrary order. And if in the case of sqlite order can be guessed, in the case of postgress the order can be surprising :) - KoVadim
  • f11 and ff11 are generally ordinary scalars, not arrays, and they will most likely not work with them. especially iterate f1 f2 f3, etc. it would be better if they stayed in an array. Yes, you can choose records in one cycle (do you have many or one records by the way?) And go as a cycle or map through an array of fields. - Mike
  • libraries have a wonderful zip function. He does half the work needed. - combines two arrays into one. - KoVadim

1 answer 1

For example:

 #!/usr/bin/env perl use Modern::Perl; use Array::Each; use DDP; my $X = [ 2, 3, 4, 5 ]; my $Y = [ 2, 3, 4, 5 ]; my @Z; my $set = Array::Each->new( $X, $Y ); while( my( $x, $y ) = $set->each() ) { push @Z, $x + $y; } p @Z; 

Conclusion:

 [ [0] 4, [1] 6, [2] 8, [3] 10 ] 

I still need to change the contents of $f11 and $ff11

To do this, you can use the third value returned by Array::Each::each() :

 while( my( $x, $y, $idx ) = $set->each() ) { # здесь $idx - индекс текущего элемента, соответственно, # доступ к элементам исходных массивов: # $X->[$idx], $Y->[$idx] } 

Well, or quite simply (only here we need explicit insurance against different sizes of arrays):

 #!/usr/bin/env perl use Modern::Perl; use DDP; my @X = ( 2, 3, 4, 5 ); my @Y = ( 2, 3, 4, 5 ); my @Z = map { # что-то делаем с $X[$_] и $Y[$_], # но в конечном итоге возвращаем # сумму элементов: ($X[$_] || 0) + ($Y[$_] || 0) } 0 .. ( $#X > $#Y ? $#X : $#Y ); p @Z;