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

Hi monks,
I am creating dynamically generated hashes, as follows:

foreach my $name(@list_of_junk){
   %{$hash_ref} = (
    "junk_name" => "$name",
    "two" => result_of_function($name)
);
#   %{$interface_hash_ref} = ("three" => "toilet"); (line deliberately commented out)
   push @interfaceref_array,    $interface_hash_ref;
   $interface_hash_ref = {};
};

Now what I'd like the commented-out line to do is add to the current hash via the reference $interface_hash_ref, but it doesn't seem to work. Any ideas why?
Cheers
Chris
  • Comment on dynamically referenced hashes ... editing

Replies are listed 'Best First'.
Re: dynamically referenced hashes ... editing
by kennethk (Abbot) on Jan 27, 2009 at 15:59 UTC
Re: dynamically referenced hashes ... editing
by AnomalousMonk (Archbishop) on Jan 27, 2009 at 19:17 UTC
    You are also, in what I assume is a typo, referencing two different hashes: $hash_ref and $interface_hash_ref.

    Per kennethk's reply, what you have might be more conscisely written (assuming use warnings; and use strict;) as:

    my @interfaceref_array; for my $name (@list_of_junk) { my $hash_ref = { # curly brackets enclose junk_name => $name, # quotes not needed two => result_of_function($name), }; do_some_stuff(); $hash_ref->{three} = "toilet"; # quotes needed for value push @interfaceref_array, $hash_ref; }
    Or even as:
    my @interfaceref_array; for my $name (@list_of_junk) { my %hash = ( # parentheses enclose junk_name => $name, two => result_of_function($name), ); do_some_stuff(); $hash{three} = "toilet"; push @interfaceref_array, \%hash; }
      Excellent :-)
      It was a typo in the example, but not in the code, I tried to simplify it for ease of reading.
      Question answered anyway
      Cheers!
      Chris