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

I am on a beginner-cgi mailing list and someone recently questioned the 'why this instead of that' in regards to one of my responces.
# The person was trying to return a result set # was doing this. $sth->execute; #his statement handle was $responce %hash = \%($responce); return %hash;
I showed him to do something like this. (Disclaimer. Normally I'd tell him to use strict, but I didn't.
$sth->execute; my $hash = {}; while(my $row = $sth->fetchrow_hashref()){ $hash->{$row->{'id'}} = $row; } return ($hash);
The next question was why $hash instead of %hash... Someone else answered, but it got me to thinking. What IS the difference between a named hash and an unnamed hash? (besides syntax)

Kristofer Hoch

Si vos can lego is, vos es super erudio

Replies are listed 'Best First'.
Re: What's the difference between named and unnamed hashes?
by broquaint (Abbot) on Jun 06, 2003 at 14:01 UTC
    A named hash is associated with one particular variable (although references to it can be created), where as an anonymous hash is refered to purely through a reference, and subsequently must live in a scalar (be it a named variable or otherwise).

    Also the syntax you provided is broken with the named hash (for anyone puzzled by the odd syntax) as the dereference is incorrect, what it needs to be is

    my %hash = %$response;
    See. perlreftut and tye's References quick reference for a quick start on references.
    HTH

    _________
    broquaint

    update: disassociated krisahoch from the dodgy syntax :)

      broquaint,

      Thank you for the quick overview, I am going to look at those references right now as well.

      PS. PLEASE DO NOT ASSOCIATE ME with that particular syntax. I did not write it!!!!

      Thanks!

      Kristofer Hoch

      Si vos can lego is, vos es super erudio

Re: What's the difference between named and unnamed hashes?
by derby (Abbot) on Jun 06, 2003 at 14:01 UTC
    Check out The PEGS notation for a way better explanation than most could do.

    -derby