sanjay nayak has asked for the wisdom of the Perl Monks concerning the following question:


The following code is well running. It is mean for if there are user defined values then it put it in the hash if the user defined values are not present, then it access the default values by calling the sub routines. I am facing little problem. By using this program i got the header values which is either default values or user defined values.But the problem is that from the same program suppose i got the values for a INVITE request, during the running of the program i suppose use this program for getting the header values of a ACK request and use this hash for it, then the values of the hash (%cnf) are not changed. It takes the previous value which is stored during the procesing of the INVITE request. How the hash values are refreshed for different requests during the execution of a program?
use strict; use warnings; sub subject { 'Subject: default subject'; } sub to { 'To: default_to@example.com'; } sub from { 'From: default_from@example.com'; } my %config = ( to => { regex => '^To:\s', sub => \&to }, from => { regex => '^From:\s', sub => \&from }, subject => { regex => '^Subject:\s', sub => \&subject }, ); my %cnf; # Load user data foreach (<DATA>) { chomp; foreach my $c (keys %config) { if (/$config{$c}{regex}/) { $cnf{$c} = $_; last; } } } # Look for missing values and fill in defaults foreach (keys %config) { unless (exists $cnf{$_}) { $cnf{$_} = $config{$_}{sub}->(); } } use Data::Dumper; print Dumper \%cnf; __DATA__ To: foo@example.com From: bar@example.com

Replies are listed 'Best First'.
Re: How the values of hash is refreshed for each request?
by GrandFather (Saint) on Oct 05, 2006 at 06:20 UTC

    What do you expect to see printed? I get:

    $VAR1 = { 'to' => 'To: foo@example.com', 'subject' => 'Subject: default subject', 'from' => 'From: bar@example.com' };

    which looks sensible to me.


    DWIM is Perl's answer to Gödel
Re: How the values of hash is refreshed for each request?
by ysth (Canon) on Oct 05, 2006 at 06:33 UTC
    Usually, and most easily, done by declaring the variable in a certain scope and leaving and reentering that scope. For instance, putting everything from my %config onward into a subroutine, and calling it as needed, perhaps having it return \%cnf. For how long after setting up %cnf do you need it?