Top


Copyright Notice

 Copyright I.N.R.A. - C.N.R.S.
 emmanuel.courcelle@toulouse.inra.fr
 jerome.gouzy@toulouse.inra.fr
 This software is a perl module whose purpose is to help you writing 
 your own scripts
 This software is governed by the CeCILL  license under French law and
 abiding by the rules of distribution of free software.  You can  use, 
 modify and/ or redistribute the software under the terms of the CeCILL
 license as circulated by CEA, CNRS and INRIA at the following URL
 http://www.cecill.info";
 As a counterpart to the access to the source code and  rights to copy,
 modify and redistribute granted by the license, users are provided only
 with a limited warranty  and the software's author,  the holder of the
 economic rights,  and the successive licensors  have only  limited
 liability.
 In this respect, the user's attention is drawn to the risks associated
 with loading,  using,  modifying and/or developing or reproducing the
 software by the user in light of its specific status of free software,
 that may mean  that it is complicated to manipulate,  and  that  also
 therefore means  that it is reserved for developers  and  experienced
 professionals having in-depth computer knowledge. Users are therefore
 encouraged to load and test the software's suitability as regards their
 requirements in conditions enabling the security of their systems and/or 
 data to be ensured and,  more generally, to use and operate it in the 
 same conditions as regards security.
 The fact that you are presently reading this means that you have had
 knowledge of the CeCILL license and that you accept its terms.

Top


NAME

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

Top


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);
   
    
=head1 DESCRIPTION

24-Jun-2004 add two new functions: IsDefined and SetUnlessDefined 26-Oct-2004 creation of Dump methods in order to export paramparser to a file or %ENV 29-Oct-2004 add the capability to define/select a NameSpace : SelectNameSpace add a fonction to get all keys matching a given pattern : GetKeys

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
        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
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.
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
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();} )
        Attach an usage fonction to the ParamParser object
__CallUsageIfNeeded
    $rh_param->__CallUsage()
    
    Private method
    Call Usage if --self specified
=cut

sub __CallUsageIfNeeded { my $self = shift; if (defined($$self{'__h_opt'}{'help'}) || defined($$self{'__h_opt'}{'HELP'})) { if ($$self{'__last_source'} =~ /CGI/i) { &Usage($self, 'html'); } else { &Usage($self); } } }

Top


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');

Top


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->Print();

Top


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
    return 1 if the behaviour passed by parameter is legal, 0 if not.
    If not loegal, croak something.
    
=cut

sub __ValidBehaviour { my ($self, $key) = @_; return 1 if ($key eq 'assert_strict'); return 1 if ($key eq 'ignore_space'); return 1 if ($key eq 'exit_on_getopt_error'); return 1 if ($key eq 'assert_empty_file_allowed'); return 1 if ($key eq 'use_substitution_table'); &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
__ToFile
        Dump the paramparser into a file
__ToENV
        Dump the paramparser into a file
__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

Top