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

Hey Wise Ones,

This is kinda a tricky question, so I'll try to word it clearly.   I have a hash.   This hash contains the name of files.   I want to beable to load an array structure or reference into the hash value.   For example

$hash{'filname'} = @array

The array structure needs to stay intact while loaded into the hash

 $array[1] = "..."; $array[2] = "...";

I need to beable to call the array items through the hash, if its possible like

 $hash{'filename'}[0]; $hash{'filanem'}[1]; etc...

I dont know if this is possible, or how I can make proper multi-level hashes.

Can someone please shed some light on this issue and show me the perly gates?

Thanks

janitored by ybiC: Replaced frowned-upon <pre> tags with <code> tags, minor format tweaks for legibility.

Replies are listed 'Best First'.
Re: Array in a hash
by tmoertel (Chaplain) on Oct 12, 2004 at 21:02 UTC

    (Update: Addressed parent's concerns about "staying intact.")

    Represent the subarrays as references to arrays. Depending on what you mean by "stay intact while loaded in the hash," you'll either want to copy or "alias" the original array's contents:

    $hash{'filename'} = [ @array ]; # copies array
    Or:
    $hash{'filename'} = \@array; # "aliases" array
    Then you can access it like ususal:
    $hash{'filename'}[0]; $hash{'filename'}[1];

    See perlref and perllol for more on this kind of thing.

    Cheers,
    Tom

      that worked, thanks Tom!
      "alias" the original array's contents

      This is more commonly referred to as referencing. Aliasing is a slightly different concept, so using the wrong term should be avoided, especially when you are talking to a newbie.

Re: Array in a hash
by qumsieh (Scribe) on Oct 12, 2004 at 21:05 UTC
    It is possible, of course. You need to read more about Perl's complex data structures. Perldsc should start you off. Hints:
    $hash{filename} = \@array; print $hash{filename}[0];