NAME

ParamParser - parse parameters from different sources (CGI.pm, GetOpt, cgi-lib, configuration file, ARGV, ENV)


SYNOPSIS

        1. parameter source defined from a configuration file
        
        use ParamParser;
        $rh_param = New ParamParser($filename);
                ------ example.cfg -------
                # lines starting with # are ignored
                OPTION=value of the option
                --------------------------
        2. from ARGV 
        
        use ParamParser;
        $rh_param = New ParamParser('ARGV');
                % program OPTION1="value of the option" OPTION2=value
 
        3. from environment variables
         
        use ParamParser;
        $rh_param = New ParamParser('ENV');
        or
        $rh_param = New ParamParser('ENV','prefix'); to add a tag to environment variables
        4. from CGI object
         
        use CGI;
        use ParamParser;
        $rh_param = New ParamParser('CGIPM');
        5. from CGI-LIB data structure (version 2)
        
        require "cgi-lib2.pl";
        use ParamParser;
        $rh_param = New ParamParser('CGILIB');
        6. from Getopt::Std object
         
        use Getopt::Std;
        use ParamParser;
        $rh_param = New ParamParser('GETOPTSTD',"list_of_singlet-character_switches");
        run the command man Getopt::Std to see what is "list_of_singlet-character_switches"
        to use  the same options with the current module you must write
        $rh_param = New ParamParser('GETOPTSTD',"oif:");
        $rh_param = New ParamParser('GETOPTSTD',"oDI");
        7. from Getopt::Long object
         
        use Getopt::Long;
        use ParamParser;
        $rh_param = New ParamParser('GETOPTLONG',(list_of_getoptlong_option));
        run the command man Getopt::Long to see what is a "list_of_getoptlong_option"
        to use the same options with the current module you must write
        $rh_param = New ParamParser('GETOPTLONG',("length=i","file=s","verbose"));
    8. from another ParamParser object
        use ParamParser;
        $rh_param = New ParamParser('PARAMPARSER',$rh_other_param);
    
    9. from a hash
    use ParamPArser;
    $rh_param = New ParamParser('HASH',\%some_hash);
   
    
=head1 DESCRIPTION
New
        see SYNOPSIS
Update
        $rh_param->Update(source,mode,GetOpt_Std_or_Long_list_of_option);
        source: CGIPM|CGILIB|GetOptStd|GetOptLong|ARGV|$filename|ENV
        mode:
                I: init : clean the data structure first
                A: append mode : preserve the previous value of duplicate keys
                O: overwrite mode : replace the value of a duplicate key
        Update the data structure with a new parameter source.
    Call Usage if a help or HELP parameter is found
Dump
        $rh_param->Dump(target[,prefix]);
        source: $filename|ENV|GetOptLong|HASH
        prefix: add the prefix 'prefix' to %ENV keys
SelectNameSpace
        $rh_param->SelectNameSpace('NS');       #  create the namespace NS (in fact a prefix to all parameters)
        $rh_param->SelectNameSpace();           #  select the namespace which contains all parameters
        Select/Init working NameSpace of parameters
Init
        $rh_param->Init();
        Initialise the data structure
Set
        $rh_param->Set($opt,$value);
        Associate a new value to $opt
SetUnlessDefined
        $rh_param->SetUnlessDefined($opt,$value);
        Associate a new value to $opt ONLY if the key is not yet defined
Delete
        $rh_param->Delete($opt);
        Delete the $opt key
Get
        $value = $rh_param->Get($opt);
        Return the value of $opt key
GetKeys
        @a_keys = $rh_param->GetKeys(pattern);
        Return a list of parameters matching the given pattern
    If the pattern is not specified, it is considered that every parameter is matched
IsDefined
        $value = $rh_param->IsDefined($opt);
        boolean, TRUE if the key is defined
HowMany
        $value = $rh_param->HowMany();
        Return the number of parameters
GetSource
        $value = $rh_param->GetSource();
        Return the last parameter source
SetSubstitution
        $rh_param->Substitute($to_substitute,$ref_substituted)
        Declare some string (format: %[a-zA-Z] to be substituted by the content of a variable or the result of a function
Print
        $rh_param->Print();
        $rh_param->Print('html');
        Print keys and associated values in text of html format
SetBehaviour
        $rh_param->SetBehaviour('assert_strict'); # when set, the assertion will fail if the parameter is not defined (default)
        $rh_param->SetBehaviour('ignore_space');  # when set, the space between the '=' are ignored in the configuration file
        $rh_param->SetBehaviour('exit_on_getopt_error') # execute the usage function when GetOptions return an error code;
        $rh_param->SetBehaviour('assert_empty_file_allowed') # when set, no exit on empty files
    $rh_param->SetBehaviour('use_substitution_table') # when set, the substitution table is used at every Set
               NOTE - When this behaviour is set, the function __SubstituteNow is called
        Control the behaviour of the parser
UnsetBehaviour
        $rh_param->UnsetBehaviour('assert_strict');              # if unset, the assertion is true when the parameter is not defined
        $rh_param->UnsetBehaviour('ignore_space');               # if unset, the space between the '=' are not ignored in the configuration file (default)
        $rh_param->UnSetBehaviour('exit_on_getopt_error')    # ignore the value returned by GetOptions (default)
        $rh_param->UnSetBehaviour('assert_empty_file_allowed') # if unset, then the program exits on empty files (default)
    $rh_param->UnSetBehaviour('use_substitution_table')    # if unset, the substitution table is ignored (default)
        Control the behaviour of the parser
GetBehaviour
    Returns 1 if the behaviour whose name is passed by parameter is set, 0 if not set.
SetDefaultBehaviour
    ParamParser::SetDefaultBehaviour($key)
    
    The default behaviour for $key is 'Set', for the objects which will be created from now on
AssertFullPath
        $rh_param->AssertFullPath(@a_opt);
        The programs stops if the key $opt does not refer to a full path of a file/dir
AssertFileExists
        $rh_param->AssertFileExists(@a_opt);
        The programs stops if the key $opt does not refer to a non empty file
AssertDirExists
        $rh_param->AssertDirExists(@a_opt);
        The programs stops if the key $opt does not refer to a directory
AssertInteger
        $rh_param->AssertInteger(@a_opt);
        The programs stops if one of the key in the list does not refer to an integer
AssertDefined
        $rh_param->AssertDefined(@a_opt);
        The programs stop if one of the key in the list is not defined
AssertAllowedValue
        $rh_param->AssertAllowedValue($value,@a_list_of_allowed_values);
        The program stop if the value of the key does not match one value of the list of allowed values
AssertAllowedPattern
        $rh_param->AssertAllowedPattern($value,@a_list_of_allowed_patterns);
        The program stop if the value of the key does not match one value of the list of allowed patterns
AssertNonEmptyFile
        $rh_param->AssertNonEmptyFile(@a_opt);
        The programs stops if the elements of the list does not refer to non empty files
Usage
        $rh_param->Usage();
        $rh_param->Usage('html');
        Print the usage of the program
SetUsage
        $rh_param->SetUsage(my $usage= sub { &my_usage_fct();} )
    or
    $rh_param->SetUsage('USAGE_DELAYED')
        Attach an usage fonction to the ParamParser object
    or
    Attach the private function UsageDelayed. If called, this function just sets a flag;
    if, somewhat later, SetUsage is called with a real function reference, this function will be immediately called.
    This way, the call of the Usage function is somewhat delayed. This can be useful when some other objects
    need to be built before calling Usage.
SetDefaultUsage
        ParamParser::SetDefaultUsage(my $usage= sub { &my_usage_fct();} )
        Attach a default usage fonction to the ParamParser module
    This function will be automagically set to the usage function for the new objects created from now
__CallUsageIfNeeded
    $rh_param->__CallUsage()
    
    Private method
    Call Usage if --help specified
=cut

sub __CallUsageIfNeeded { my $self = shift; if ($self->IsDefined('help') or $self->IsDefined('HELP')) { return if (defined($$self{'__usage_delayed'}) && $$self{'__usage_delayed'}==1); if ($$self{'__last_source'} =~ /CGI/i) { &Usage($self, 'html'); } else { &Usage($self); } } }

sub __UsageDelayed { my $self = shift; $$self{'__usage_needed'} = 1; # We shall call Usage when possible };


EXAMPLE1

        use CGI qw/:standard/;
        use ParamParser;
        my $rh_param =  New ParamParser("CGIPM");
        $rh_param->SetUsage(my $usage=sub { print "\nPlease read the documentation\n"; } ); # attach an usage fonction to the parser
        # the best way is to reference a real fonction $rh_param->SetUsage(my $usage=sub { &UsageFct(); } );
        $rh_param->Set('TIMEOUT','10000');  # add a single variable to the data structure
        $rh_param->Update('ENV',"O");      # append all environment variables in overwrite mode (overwrite duplicates)
        $rh_param->AssertFileExists('CFG'); # check that the value of the parameter CFG is an existing file, print the usage and exit if it is not.
        $rh_param->Update($rh_param->Get('CFG'),"A");      # add all variables contained in the configuration file in append mode (do not overwrite duplicates)
        print header;
        $rh_param->Print('html');


EXAMPLE2

        use Getopt::Long;
        use ParamParser;
        my $rh_param =  New ParamParser('GETOPTLONG',("help:s","min=i","max=i","inputfile=s","what=s"));
        $rh_param->SetUsage(my $usage=sub { print "\nPlease read the documentation\n"; } ); # attach an usage fonction to the parser
        # the best way is to reference a real fonction $rh_param->SetUsage(my $usage=sub { &UsageFct(); } );
        $rh_param->Update('ENV',"A");      # append all environment variables in append mode (do not overwrite duplicates)
        $rh_param->AssertFileExists('inputfile');               # check that the value of the parameter inputfile is an existing file, print the usage and exit if it is not.
        $rh_param->AssertInteger('max','min');  # check that the value of the parameters are integers, print the usage and exit if one of them is not.
        $rh_param->AssertAllowedValue('what','yes','no','maybe');  # check that the value of the parameters is a correct value
        $rh_param->AssertAllowedPattern('^[wW]hat$','^[yY]es', '^[nN]o','^maybe$');  # check that the value of the parameters is a correct value, matching one of those patterns 
        $rh_param->Print();


INTERNAL METHOD CALLS

__PrintUsage
        Print the usage of the program
__UpdateIfPossible
        Update the value of the given key, depending on the selected insertion mode
__ValidBehaviour
    __ValidBehaviour is a funtion, NOT a method - No $self arg
    return 1 if the behaviour passed by parameter is legal, 0 if not.
    If not legal, croak something.
    
=cut

sub __ValidBehaviour { my $key = shift; return 1 if (exists $H_DEFBEHAVIOUR{$key}); &Carp::croak(``\n=>The behaviour $key is unknown''); return 0; }

__SubstituteKey
    Try to make the substitutions for the key passed by parameter
    
=cut

sub __SubstituteKey { my ($self, $key) = @_; return unless (defined($self->{'__h_opt'}{$key})); # If value not defined, nothing to substitute return unless (exists $self->{'__substitution_table'}); # If no table, nothing to substitute


    my $rh_sub_table = $self->{'__substitution_table'};
    my $to_subst     = $self->{'__h_opt'}{$key};
    return unless ($to_subst =~ /%/);                           # If no %, nothing to substitute

    foreach my $s (keys(%$rh_sub_table))
    {
        next unless ($to_subst =~ /$s/);
        my $r = $rh_sub_table->{$s};
        if (ref($r) eq 'SCALAR')            # Substitute if ref to a scalar
        {
            $to_subst =~ s/$s/$$r/g;
        };
        if (ref($r) eq 'CODE')              # Substitute, calling the sub, if ref to a sub
        {
            my $subst = &$r($self,$key);
            $to_subst =~ s/$s/$subst/g;     # N.B. May be several substitutions, but only 1 call
        };
    }

    $self->{'__h_opt'}{$key} = $to_subst;
    return;
}
__SubstituteAll
    For each parameter, call __SubstituteKey
    
=cut

sub __SubstituteAll { my $self = shift; foreach my $key (sort keys(%{$self->{'__h_opt'}})) { $self->__SubstituteKey($key); } }

__FromGetOptStd
        Initialize the ParamParser object using Getopt::Std style as source of param/values
__FromGetOptLong
        Initialize the ParamParser object using Getopt::Long style as source of param/values
__FromCGILIB
        Initialize the ParamParser object using CGI-LIB2 as source of param/value
__FromCGIPM
        Initialize the ParamParser object using CGI.pm source
__FromFile
        Initialize the ParamParser object using a configuration file.
__FromARGV
        Initialize the ParamParser object using the @ARGV array as source of param/values
__FromENV
        Initialize the ParamParser object using the %ENV hash as source of param/values
__FromPARAMPARSER
        Initialize the ParamParser object using another ParamParser object
__FromHASH
        Initialize the ParamParser object using a hash
__ToFile
        Dump the paramparser into a file
__ToENV
        Dump the paramparser into the environment
__ToHASH
        Dump the paramparser into a HASH
__ToGetOptLong
        Dump the paramparser to @ARGV, using OptLong conventions
__DefinedIfNot
        Init a variable if it is not defined (in order to avoid warnings)
__InitPossibleSources
        Build a list of possible sources depending on loaded modules