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

Below i have got the code which works well with right output , But I was wondering if there is any other smarter way to reduce number of code doing same jobs? Any one have any suggestion, please let me know!
#Check environment sub inspect { my $window,$informix,$oracle,$sql) = @_; if ($^O eq 'MSWin32' or $^O eq 'Windows_NT') { $window=1; } if ($ENV{FRUNEXT}) { if ($ENV{FRUNEXT} eq 'ifx') { $$informix=1; } elsif($ENV{FRUNEXT} eq 'msv') { $$sql=1; } elsif($ENV{FRUNEXT} eq 'ora') { $$oracle=1; } } else { err_msg( "Database Environment Variable 'FRUNEXT' Not Set: $!\ +n"); exit; } }
Cheers!

Replies are listed 'Best First'.
Re: Checking environment smart solution
by Corion (Patriarch) on Jun 24, 2009 at 07:15 UTC

    Also, instead of passing references to your subroutine, you'll be much better off returning a hash, potentially eliminating the $oracle and $informix variables in favor of a $database variable, which contains either "Oracle" or "Informix".

Re: Checking environment smart solution
by ikegami (Patriarch) on Jun 24, 2009 at 14:25 UTC

    Don't split one value into 4 variables, only one of which can be true.

    Don't include $! in your error message. You didn't do any system calls that set $!.

    Why aren't you using die? It'll be much more simpler and reliable to catch exceptions and/or STDERR rather than using errmsg everywhere.

    sub inspect { return "windows" if $^O eq 'MSWin32' || $^O eq 'Windows_NT'; my $frunext = $ENV{FRUNEXT} or die("Environment variable 'FRUNEXT' not set\n"); return $frunext if $frunext =~ /^(?:ifx|msv|ora)$/; return ''; }
    Or if you want to do some translation:
    my %db_lkup = ( ifx => 'informix', msv => 'sql', ifx => 'oracle', ); sub inspect { return "windows" if $^O eq 'MSWin32' || $^O eq 'Windows_NT'; my $frunext = $ENV{FRUNEXT} or die("Environment variable 'FRUNEXT' not set\n"); return $db_lkup{$frunext} if exists( $db_lkup{$frunext} ); return ''; }

    I didn't know if you meant for an unrecognized value of $ENV{FRUNEXT} to be an error. It wasn't, so I didn't change that.

Re: Checking environment smart solution
by Anonymous Monk on Jun 24, 2009 at 06:20 UTC
    Read perlintro.
    err_msg( "Database Environment Variable 'FRUNEXT' Not Set: $!\n") unle +ss $ENV{FRUNEXT} =~ /^ifx|msv|ora$/
Re: Checking environment smart solution
by citromatik (Curate) on Jun 24, 2009 at 07:33 UTC

    If you are using Perl 5.10, the give...when construction may be of interest here (see perlsyn:

    use feature qw/ :5.10 /; # or just: use feature "switch"; sub inspect { my $window,$informix,$oracle,$sql) = @_; $$window=1 if ($^O eq 'MSWin32' or $^O eq 'Windows_NT'); given ($ENV{FRUNEXT}) { when ('ifx') { $$informix=1; } when ('msv') { $$sql=1; } when ('ora') { $$oracle=1; } default { err_msg( "Database Environment Variable 'FRUNEXT' Not Se +t: $!\n") && exit } }

    citromatik