Newbie question

At this point, in any other language, I'd lean toward creating a multidimensional array from those key=value pairs, but I don't think I can do that in perl. Here's where I'm stuck:

Code:

foreach(@array){
@stuff = split('=', $_);
# this is where I'm stuck
}

Assuming that $input isn't empty which it can be, I can reference $stuff[0] and $stuff[1] for the key/value pairs. How can I stuff those into a list so that later on I can iterate through them in a loop? I tried $x[$stuff[0]] = $stuff[1], but no go.

It'd be nice if I could understand it as well, but I'll settle for an esoteric oneliner too.

There is no guarantee that they will be stored in the same order as they are added. However, you can sort them as you loop over the pairs, or you can use a module such as Tie::IxHash to preserve the order in which the hash elements were added. It uses an array behind the scenes to maintain that order.

Before I saw your last message, Fishmonger, I was just going to suggest two codes snippets using the map function almost exactly identical to your two first code snippets, but I was taken by surprise when looking at the last one, which I did not think of and which, I must, say, is pretty clever.

Before I saw your last message, Fishmonger, I was just going to suggest two codes snippets using the map function almost exactly identical to your two first code snippets, but I was taken by surprise when looking at the last one, which I did not think of and which, I must, say, is pretty clever.

It may be clever, but it's not really what I'd do in production code. I included it more for completeness.

I guess a hash is sort of like an associative array in other languages which is what I was after. There really isn't a need for sorting or other ordering techniques. I was just curious how that worked since FishMonger's original code sample did not have random output at all -- it was identical ordering every time I ran it. Good stuff though.

Since you guys are so willing to share though, I've noticed that when working with individual hash keys you can reference them with or without quotes. Is there a difference between $hash{key} and $hash{'key'}?

Yes, the keys don't come in random order, but in what seems to be random order. Whether you use the keys, the values or the each function, it will be each time the same order, which is in fact dependent on the way the keys and values are stored internally by Perl. And yes, a hash is one form of associative array.

As for the use of quotes, Perl "stringifies" the keys, i.e. transforms them into strings, which is why quotes are not necessary. So that using quotes or not usually does not make a difference.