Search code examples
arraysperl

Perl: change element/s in array of hashes


How do I change an element/s in an array of hashes in Perl?

Suppose I have the following array and want to change the price of an item:

my @clothes = (
    { item => 'Jeans',  colour => 'Blue',  price => 50 },
    { item => 'Shawl',  colour => 'Red',   price => 30 },
    { item => 'Blazer', colour => 'Brown', price => 100 },
    { item => 'Suit',   colour => 'Black', price => 40 },
    { item => 'Top',    colour => 'White', price => 25 }
);

Solution

  • You don't have a two-dimensional array---you have an array of hashrefs. If you wanted to change the price of a specific item, you would need to know the array index that holds the hash reference it belongs to.

    $clothes[1]->{price} = 42;
    

    For additional things you can do with your array of hashes, see the aptly named Arrays of Hashes section of perldsc.