in reply to Using an array in a hash

Instead of directly answering your question (which other people have already done, well) I'll give you a few quick pointers on perl references (which other people will probably also do). First, you might want to take a look at perlref, (i.e. type perldoc perlref), it contains a pretty good explanation of how to use references in perl.

Basically, references are scalars, if you have a C background, just think of them as pointers, the only difference being that you can't do pointer arithmetic on them. (i.e. no $myref++; or similar).

Also, since perl is not a strongly typed language, you are responsible for keeping track of what data type a reference points to. There's no such thing as an 'array reference' or a 'hash reference', just a reference, which can point to either an array or a hash.

Some examples of referencing and dereferencing

# create a 'real' array and a reference to it. my @array = (1, 2, 3, 4); my $reftoactualarray = \@array; # create a reference to an anonymous array my $reftoanonymousarray = [1, 2, 3, 4]; # both print the same thing print @$reftoactualarray; print @$reftoanonymousarray;
The difference between a 'real' array and an anonymous one is that when you modify the array referenced by $reftoactualarray, the contents of @array actually change. If you change the array referenced by $reftoanonymousarray, nobody else will see the changes you made. Dereferencing arrays of hashes or hashes of arrays, or any complex data structure like that, can get pretty hairy.

Good Luck,

Corrections welcome.

Replies are listed 'Best First'.
Re^2: Using an array in a hash
by Anonymous Monk on Jan 22, 2005 at 19:47 UTC
    The person asked for how to get a array back OUT OF A HASH. None of you have answered the question. I would like to know how to do this as well. Here what I tried and it failed. my @host_type= qw { a b c d e} ; my $j = "small" ; my %vendor_size_hash = ($j => \@host_type ) ; print "\@vendor_size_hash{$j} \n " ;
      There are two ways to dereference an array, depending on what you need to do. See perlref and perlreftut for the details.

      In short, to dereference an entire array, use:

      my @array = @{ $vendor_size_hash{$j} };
      To dereference a single element in the array, use:
      my $el = $vendor_size_hash{$j}[$number];