Note that there are some explanatory texts on larger screens.

plurals
  1. POLooping over an array to build a multidimensional array in Perl, converting from PHP, and syntactically wrong
    primarykey
    data
    text
    <p>Working on converting an array to another array. In PHP, this is easy, but Perl has some syntax that I am having a hard time getting my head around and understanding.</p> <p>Here is my loop in Perl:</p> <pre><code>foreach my $r (@toindex){ #print Dumper $r; %indexed{@$r[0]}{'image_id'} = @$r[0]; #Broken %indexed{"@$r[0]"}{'image_id'} = @$r[0]; #Broken } </code></pre> <p>Here is my @toindex array</p> <pre><code>$VAR1 = [ [ 3638584, 'Aperture', 'F13' ], [ 3638588, 'Exposure Bias', '0 EV' ], [ 3638588, 'Focal Length', '80.0 mm' ], ]; </code></pre> <p>And here is what I want to do, but in PHP</p> <pre><code>foreach($indexrows as $k =&gt; $v){ $indexed[$v['image_id']]['image_id'] = $v['image_id']; } </code></pre> <p>It seems so very simple in PHP, but moving it to Perl is proving to be quite a challenge for me.</p> <hr> <p>Update</p> <p>Thanks to the help of Sinan Ünür and DVK with that final little pointer, I have a working solution. I'm posting the complete script in case anyone might find some part of it useful in the future.</p> <pre><code>#!/usr/bin/perl use strict; use warnings; use DBI; use Data::Dumper; my $dbh = DBI-&gt;connect('dbi:Pg:dbname=database;host=serveraddress','user','password') or die; my $sth; my $sql = "SELECT id, field, data FROM table"; my $offset = 0; my $increment = 20; my $toindex; # This loop here is to solve a problem that was not part of the # original question. I included it to illustrate the syntax for # looping a database query do{ $sth = $dbh-&gt;prepare($sql . " LIMIT " . $increment . " OFFSET " . $offset); $sth-&gt;execute or die; $toindex = $sth-&gt;fetchall_arrayref; $offset = $offset + $increment; }while(@$toindex == 0); # Alternately, if you do not need a loop below is all you need # $sth = $dbh-&gt;prepare($sql); # $sth-&gt;execute or die; # $toindex = $sth-&gt;fetchall_arrayref; my %indexed; foreach my $r ( @$toindex ) { #print Dumper $r; my ($id, $field, $value) = @$r; @{ $indexed{ $id } }{('image_id', $field)} = ($id, $value); } print Dumper %indexed; $dbh-&gt;disconnect; </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload