christiffer has asked for the wisdom of the Perl Monks concerning the following question:

i've got the following code snippet to decypher:
my %h = (); @h{@FIELDS} = @row; $result = \%h;
Am I right in thinking that this places the contents of @row in a hash table, with keys from @FIELDS ? @row is from DBI::fetchrow_array(), so fields must exactly match the column names in the DB?

Replies are listed 'Best First'.
Re: Hash newbie
by ikegami (Patriarch) on Jan 28, 2005 at 15:37 UTC

    Exactly. Your snippet is equivalent to:

    my %h = (); foreach (0..$#FIELDS) { $h{$FIELDS[$_]} = $row[$_] } $result = \%h;

    It's called a hash slice, and it should be documented in perldata.

      (FX: perldoc perldata). Aha! I have achieved a limited form of enlightenment. Thank you for endulging my laziness ;)

        ikegami explained that this uses a hash slice. He also showed an equivalent snippet that has the same effect as yours. But I'd like to show an equivalent snippet that might help you understand how the hash slice is doing its job:

        my %h = (); # @h{@FIELDS} = @row; ($h{$FIELDS[0]}, $h{$FIELDS[1]}, $h{$FIELDS[2]}, ...) = ( $row[0] , $row[1] , $row[2] , ...); $result = \%h;

        As you can see, a hash slice is simply a convenient syntax for doing something that is not altogether very complicated. Hopefully this helps you understand it.

Re: Hash newbie
by Jasper (Chaplain) on Jan 28, 2005 at 17:10 UTC
    what's wrong with  fetchrow_hashref ?

      We don't know that he's necessarily using DBI, and, moreover, The OP was asking for explanation of a snippet he didn't understand. He wasn't asking for advice on how to refactor the code.

      Update: Sorry for not reading the whole post. I still think the OP was simply asking for help understanding a snippet of code, and the context wasn't as important, but I should have read the question all the way.

        We don't know that he's necessarily using DBI,

        We do. He explicitely stated that @rows comes from DBI::fetchrow_array().

        He wasn't asking for advice on how to refactor the code.

        Maybe not, but the OP's question was answered, and it's tradition to offer alternatives, especially when they are better.