in reply to (Ovid) Re: creating a particular hash
in thread creating a particular hash

you already got lots of code answers, but not a lot of explanation, so i'll go light on the former and heavy on the latter.

conceptually, it isn't bad to split it into two arrays, because you can then refer to a hash slice. given this:

my %hash; my @keys = (1, 2, 3, 4, 5); # an array of hash keys my @values = qw(one two three four five); # array of values
you can say
@hash{@keys} = @values;
that array prefix (@) tells perl you're going to be dealing with a list out of that hash, rather than a scalar. the array in the curlies ({}) tells perl what keys to use; @hash{@keys} is effectively the same as saying ($hash{$keys[0]}, $hash{$keys[1]}, $hash{$keys[2]}, ...). then you assign them all at once from the array of values; this works just like any list assignment.

of course, you didn't start with those two arrays, so you have to make them in order to use them, but that's OK; the split statements shown will work, and you sounded like you knew how to do that anyway.

.

actually, if you really are using integer keys, you might want to consider putting them into an array rather than into a hash; it depends what else is going on. but

@array[@keys] = @values
will work just as well, for the example you've shown, and take much less memory.

another handy thing to keep in mind is that you can use the range operator to create that list for you.

@words_array[1..12] = qw(one two three four five six seven eight nine +ten eleven twelve); @words_hash{(1..12)} = qw(one two three four five six seven eight nine + ten eleven twelve);
but now i'm sure i've digressed. for more information, look up array and hash slices. (Note: this deals more with multidimensional slices, but i couldn't find better documentation on straight slices.)

update hash slices are forgettable; they read funny, they seem weird, and they're fundamentally useful. how's that for trouble? who would expect to be able to talk about a list of things from an unordered pile of associations? anyway, there are things i'd like hash slices to do that they don't.

Replies are listed 'Best First'.
Re: (Vynce) Re: (Ovid) Re: creating a particular hash
by michellem (Friar) on Jun 01, 2001 at 18:54 UTC
    Wow, thanks for the explanation! Those hash slices are cool, and did just what I wanted them to.