FAQ
Hi Satya,

I do not know whether you can use Tie::Hash?
This is my try:

use strict;
use warnings;
use Data::Dumper;
use TieReadOnly;
tie my %hash, "TieReadOnly";
%hash=( name => "satya", number => "21");
print ("\nBefore ".Dumper(\%hash));

$hash{name}="new name";
print ("\nAfter ".Dumper(\%hash));

package TieReadOnly;
use Tie::Hash;
use Carp;
our @ISA = 'Tie::StdHash';

sub STORE {
     my ($self, $key, $value) = @_;
     if ($self->{$key}){
         carp "The value is read only. You failed";
     }else{
         $self->{$key} = $value;
     }
}

The output is like this:

Before $VAR1 = {
           'name' => 'satya',
           'number' => '21'
         };
The value is read only. You failed at tst.pl line 22.

After $VAR1 = {
           'name' => 'satya',
           'number' => '21'
         };
dhcp-892b2e52:Perl logust$
On 12 May 2014, at 09:59, Satya Prasad Nemana wrote:

Hi

I have requirement to make the key of a perl hash to be read only so that no other function can modify it.

I got Hash::Util package and managed to do what I needed

use strict;
use warnings;
use Hash::Util qw (lock_keys lock_value);
use Data::Dumper;
my %hash=( name => "satya", number => "21");
my $ref=\%hash;
print ("\nBefore ".Dumper(%hash));
lock_value(%hash,"name");
$hash{name}="new name";
print ("\nAfter ".Dumper(%hash));

The problem is that now I get the error

snemana@bats4:~/perlprogs>$perl lock_hash_keys.pl

Before $VAR1 = 'number';
$VAR2 = '21';
$VAR3 = 'name';
$VAR4 = 'satya';
Cannot usefully lock values in an unlocked hash at lock_hash_keys.pl line 10
Modification of a read-only value attempted at lock_hash_keys.pl line 11.

As seen above the program halts when the attempt is made to assign value to the hash key.
What I wanted is way to stop the assignment and throw and error but not halt the program, but continue with the program.

Could someone help me with the error handling please?

Thanks,
Satya

Search Discussions

Discussion Posts

Previous

Follow ups

Related Discussions

Discussion Navigation
viewthread | post
posts ‹ prev | 6 of 7 | next ›
Discussion Overview
groupbeginners @
categoriesperl
postedMay 12, '14 at 8:59a
activeMay 13, '14 at 3:51p
posts7
users5
websiteperl.org

People

Translate

site design / logo © 2021 Grokbase