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

Replies are listed 'Best First'.
•Re: Hash from DBI
by merlyn (Sage) on Apr 30, 2003 at 09:32 UTC
    Maybe I'm being dense this morning but won't this do it:
    while (my $ret = $sth->fetchrow_hashref) { my %user = %$ret; ... }
    Although I would argue that your code is making an unnecessary copy of an unnecessary copy. So hopefully you aren't optimizing for performance... just programmer flexibility.

    -- Randal L. Schwartz, Perl hacker
    Be sure to read my standard disclaimer if this is a reply.

      Or even more directly
      while (my %user = %{ $sth->fetchrow_hashref }) { ... }

      HTH

      _________
      broquaint

Re: Hash from DBI
by nite_man (Deacon) on Apr 30, 2003 at 11:11 UTC
    I would like to suggest you retrive all rows of query execute result for one time:
    use DBI; . . . my $res = $sth->fetchall_arrayref(); # Returns array ref with all resu +lt rows which are array refs too. for my $row (@$res) { for my $value (@$row) { print "$value " } print "\n"; }
    or
    my $res = $sth->fetchall_arrayref({}); # Returns array ref with result + rows which are hash refs. for my $row (@$res) { for my $key (%$row) { print "$$row{$key} " } print "\n"; }
          
    --------------------------------
    SV* sv_bless(SV* sv, HV* stash);
    
Re: Hash from DBI
by hmerrill (Friar) on Apr 30, 2003 at 14:20 UTC
    Why not do something like this:
    while ($user_hashref = $sth->fetchrow_hashref) { print "name = $user_hashref->{username}\n"; print "email = $user_hashref->{email}\n"; }

    The hashref that fetchrow_hashref gives you back doesn't necessarily need to be turned back into another hash to be used - you can use the hashref($user_hashref above) to point at individual element values using the greater than(->) notation.

    HTH.
Re: Hash from DBI
by gmpassos (Priest) on May 01, 2003 at 04:02 UTC
    Well, this isn't really a DBI question.

    First you can use the hash reference inside of the scalar very similar to a normal hash, just use $$hash{foo}:

    my $hash_ref = { a => 1 , b => 2 , } ; print "$$hash_ref{a}\n" ; print "$$hash_ref{b}\n" ;

    But if you really want to use $hash{foo} directly, without make a copy, use this code:

    my $hash_ref = { a => 1 , b => 2 , } ; local(*hash) ; *hash = $hash_ref ; print "$hash{a}\n" ; print "$hash{b}\n" ;
    But note that %hash is declared inside *hash, with local() to simulate the my %hash! And any other variable or handle with the name hash will be overwrited. In other words, local() works for: $hash, @hash, %hash, hash

    Graciliano M. P.
    "The creativity is the expression of the liberty".