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

In below code I am checking if $options are defined or not, if not then i am assigning respective file name to variables but without defined it work but with defined i am getting 1 as a value for variable rather than actual value, Any suggestion?please,
my $source_file= defined($options{o}) || 'as.xcf-dist'; my $config_file= defined($options{c}) || 'config.ini'; my $dest_file= defined($options{x}) || usage();

Replies are listed 'Best First'.
Re: checking $option
by targetsmart (Curate) on Jun 26, 2009 at 05:02 UTC
    from defined
    Returns a Boolean value telling whether EXPR has a value other than the undefined value undef. If EXPR is not present, $_ will be checked.

    you are getting a true boolean value 1, which means when the option is present, you are just storing the return value of defined($options{o})

    try ? :

    my $source_file = defined($options{o}) ? "<some filename>" : "as.xcf-d +ist" ;


    Vivek
    -- 'I' am not the body, 'I' am the 'soul', which has no beginning or no end, no attachment or no aversion, nothing to attain or lose.
Re: checking $option
by ikegami (Pope) on Jun 26, 2009 at 07:34 UTC

    This wouldn't be an issue at all if you used the standard module Getopt::Long.

    Anyway,

    my $source_file = defined($options{o}) ? $options{o} : 'as.xcf-dist';

    or

    my $source_file = 'as.xcf-dist'; $source_file = $options{o} if defined($options{o});

    or

    my $source_file = $options{o}; $source_file = 'as.xcf-dist' if !defined($options{o});

    or

    sub defined_or { defined($_[0]) ? $_[0] : $_[1] } my $source_file = defined_or( $options{o}, 'as.xcf-dist' );

    or

    # Requires 5.10 my $source_file = $options{o} // 'as.xcf-dist';
Re: checking $option
by citromatik (Curate) on Jun 26, 2009 at 07:38 UTC

    If you are using a Perl version >= 5.10 you can also use the // operator (see perlop):

    my $source_file = $options{o} // 'as.xcf-dist'; my $config_file = $options{c} // 'config.ini'; my $dest_file = $options{x} // usage();

    citromatik

Re: checking $option
by leslie (Pilgrim) on Jun 26, 2009 at 05:13 UTC
    Dear friend,
    Check the defined method.It always return boolean value.. 
    If values already defined it will return "true(1)" else "false".
     If $option is not define it will take the file name and assigned to that variable..
    If already defined it will return 1. So u will get 1 as a value..
Re: checking $option
by Anonymous Monk on Jun 26, 2009 at 05:03 UTC
    perldoc -f defined

    Ieturns a Boolean value telling whether EXPR has a value other than the undefined value undef. If EXPR is not present, $_ will be checked.

Re: checking $option
by toolic (Bishop) on Jun 26, 2009 at 13:32 UTC