Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 238
  • Last Modified:

hashes and array of hashes

I have an array of hashes and a hash, i needed to check the values of both and if they are different replace the key/value pair in the array of hashes with the key value pair in the hash. For example the key value pair NAME => 'Y' in the AoH is different from the %default, I need to replace this for NAME=>'N' in the array of hashes. Can somebody help me with this?

Thanks!
 

$VAR1 = [
           {'NAME' => 'Y',
            'FILE' => 'file.txt',
            'YEAR' => '1988'}
 
        ]
 
%default = {'MODE' = '2', ''NAME' => 'N','FILE' => 'file.txt', 'YEAR' => '1987'}

Open in new window

0
cucugirl
Asked:
cucugirl
  • 2
1 Solution
 
Adam314Commented:
What do you want to do when the AoH contains a key that doesn't exist in %default?  This code skips those...

Also, in your definition for %default, you want to use (), not {}, as you will be creating a hash reference.

my $VAR1 = [
           {'NAME' => 'Y',
            'FILE' => 'file.txt',
            'YEAR' => '1988'}
 
        ];
 
my %default = ('MODE' => '2', 'NAME' => 'N','FILE' => 'file.txt', 'YEAR' => '1987');
 
foreach my $hash (@$VAR1) {
	foreach my $key (keys %$hash) {
		next unless exists($default{$key});
		$hash->{$key} = $default{$key};
	}
}
 
print Dumper($VAR1);

Open in new window

0
 
ozoCommented:
$VAR1 = [
           {'NAME' => 'Y',
            'FILE' => 'file.txt',
            'YEAR' => '1988'}
 
        ];
 
%default = ('MODE' => '2', 'NAME' => 'N','FILE' => 'file.txt', 'YEAR' => '1987');


@$VAR1 = map{ {%default,%$_} } @$VAR1 ;

0
 
ozoCommented:
#sorry, I was thinking $VAR1 would override the default, but it sounds like you want the default to override $VAR1
@$VAR1 = map{ {%$_, %default} } @$VAR1 ;
#or
@{$_}{keys %$_}=@default{keys %$_} for @$VAR1;
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now