syker
syker

Reputation: 11272

Modifying hash within a hash in Perl

What is the shortest amount of code to modify a hash within a hash in the following instances:

%hash{'a'} = { 1 => one, 
               2 => two };

(1) Add a new key to the inner hash of 'a' (ex: c => 4 in the inner hash of 'a') (2) Changing a value in the inner hash (ex: change the value of 1 to 'ONE')

Upvotes: 2

Views: 891

Answers (2)

Daenyth
Daenyth

Reputation: 37441

Based on the question, you seem new to perl, so you should look at perldoc perlop among others.

Your %hash keys contain scalar values that are hashrefs. You can dereference using the -> operator, eg, $hashref = {foo=>42}; $hashref->{foo}. Similarly you can do the same with the values in the hash: $hash{a}->{1}. When you chain the indexes, though, there's some syntactic sugar for an implicit -> between them, so you can just do $hash{a}{1} = 'ONE' and so on.

This question probably also will give you some useful leads.

Upvotes: 1

Greg Bacon
Greg Bacon

Reputation: 139461

$hash{a}{c} = 4;

$hash{a}{1} = "ONE";

Upvotes: 1

Related Questions