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

Hello,
If I want to reference an item in a hashref like this:

$hash_ref->{'sender'}

How do I build the data structure?

Can I just say,

my $hash_ref; $hash_ref->{'sender'}='address'; $hash_ref->{'date'}='date'; etc

I assume this is just refering to an array of hashrefs right?

@{$q_mail}

Your help greatly appreciated as always.

Tom

Replies are listed 'Best First'.
Re: Building Hashrefs
by pbeckingham (Parson) on Jul 23, 2004 at 14:37 UTC

    For hash refs:

    my $hash_ref = {}; # valid hash_ref, empty hash $hash_ref->{'key'} = 'value'; # hash now contains one k-v pair # but hash_ref unchanged
    The following code is just dereferencing an array ref.
    @{$q_mail}

Re: Building Hashrefs
by Fletch (Bishop) on Jul 23, 2004 at 14:38 UTC

    perldoc perlreftut, perldoc perldsc, perldoc perllol, perldoc perlref.

Re: Building Hashrefs
by deibyz (Hermit) on Jul 23, 2004 at 14:42 UTC
    Hi,

    First, perldoc perlref is your friend!
    Have a look and your life will be much better.

    In your example, the structure $scalar->{} will autovivify (*) an anonymous HASH reference, just as:

    my $hash_ref = {}; ${$hash_ref}{foo} = "bar";

    (*) More about autovivification: http://tlc.perlarchive.com/articles/perl/ug0002.shtml

    Updated: Fixed typos =/

      You have omitted the sigil on your declaration, and misspelled the variable while dereferencing it for some reason.

      my $hash_ref = {}; $hash_ref->{foo} = "bar";

        Thanks, Fridays are so bad...
        Updated.