Try using a hash with the named params as keys like this:

my %session_params = ( hostname => $ARGV[0], port => $ARGV[6], version => $ARGV[5] ? "snmpv" . $ARGV[5] : '', timeout => $ARGV[7], ... # and so on for all params }; for ( keys( %session_params ) { delete( $session_params{$_} unless $session_params{$_}; } my ( $session, $error ) = Net::SNMP->session( %session_params ); # Update: # allowed for an empty string for an arg that was being manipulated: $ +ARGV[5]
This is a very simple example, but I think you get the idea. You can see how I use a similar approach which includes setting default values if you view the source for DateTimeX::Fiscal::Fiscal5253.

I would consider using Getopt::Long and have named params on the command line to make life a little bit easier.

Update: Here is the direct solution to what you gave:

#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my $foo = 1; my $bar = 'baz'; my $baz = ''; my %foohash = ( $foo ? ( foo => $foo ) : (), bar => $bar, $baz ? ( baz => $baz ) : (), $ARGV[0] ? ( version => 'snmpv' . $ARGV[0] ) : () ); print Dumper(\%foohash); exit; __END__ Output: $VAR1 = { 'bar' => 'baz', 'foo' => 1 };

No matter what approach you take, I strongly advise doing some parameter validation before using them!

You must always remember that the primary goal is to drain the swamp even when you are hip-deep in alligators.

In reply to Re: Optionally include named arguments when constructing a new object by boftx
in thread Optionally include named arguments when constructing a new object by nice_iguana

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.