Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way make perl compilation fail if a hash key wasn't defined in the initial hash definition?

All keys used should be present in the initial %hash definition.

use strict;
my %hash = ('key1' => 'abcd', 'key2' => 'efgh');
$hash{'key3'} = '1234'; ## <== I'd like for these to fail at compilation. 
$hash{'key4'}; ## <== I'd like for these to fail at compilation.

Is there a way to do this?

like image 406
Nuncio Avatar asked Jan 18 '23 14:01

Nuncio


1 Answers

The module Hash::Util has been part of Perl since 5.8.0. And that includes a 'lock_keys' function that goes some way to implementing what you want. It gives a runtime (not compile-time) error if you try to add a key to a hash.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Hash::Util 'lock_keys';

my %hash = (key1 => 'abcd', key2 => 'efgh');
lock_keys(%hash);
$hash{key3} = '1234'; ## <== I'd like for these to fail at compilation. 
say $hash{key4}; ## <== I'd like for these to fail at compilation.
like image 151
Dave Cross Avatar answered Jan 31 '23 06:01

Dave Cross