I have a hash in which I store the products a customer buys (%orders). It uses the product code as key and has a reference to an array with the other info as value.
At the end of the program, I have to rewrite the inventory to the updated version (i.e. subtract the quantity of the bought items)
This is how I do rewrite the inventory:
sub rewriteInventory{
open(FILE,'>inv.txt');
foreach $key(%inventory){
print FILE "$key\|$inventory{$key}[0]\|$inventory{$key}[1]\|$inventory{$key}[2]\n"
}
close(FILE);
}
where $inventory{$key}[x] is 0 → Title, 1 → price, 2 → quantity.
The problem here is that when I look at inv.txt afterwards, I see things like this:
CD-911|Lady Gaga - The Fame|15.99|21
ARRAY(0x145030c)|||
BOOK-1453|The Da Vinci Code - Dan Brown|14.75|12
ARRAY(0x145bee4)|||
Where do these ARRAY(0x145030c)||| entries come from? Or more important, how do I get rid of them?
EDIT: I was wrong about having to use an explicit dereferencing arrow; this is inferred between brackets when necessary, even if the first brackets do NOT require a dereference. That said, I will leave the remainder of the answer as posted since it was accepted, but merely note that if you choose not to use
join, you needn’t actually use$inventory{$key}->[0]but can in fact use$inventory{$key}[0]as originally posted.Just be aware that the first (hash) brackets do not imply a dereference but the second (array) brackets do. Your errant array refs in the output were coming from looping over not only keys but also values of the hash.
ORIGINAL ANSWER:
In addition to using
keys, you also need to dereference the references-to-array (this is why you’re seeing each value output as ARRAY with an address—you’re printing the references, not the values of the dereferenced array) when you print, so your loop becomes something like:I’d probably rewrite it a little more idiomatically as:
Hope that helps!