Errormsgs on GetOptions

Discussion in 'Perl Misc' started by Tom Gur, Dec 17, 2007.

  1. Tom Gur

    Tom Gur Guest

    Hi,

    I'm using GetOptions in the following manner:
    $getoptions_rc = GetOptions( "host=s" => \$host, "port=n" => \$port);
    Now, in case the user inputs something wrong, like a letter in the
    port - GetOption prints a default errormsg.
    how can I suppress the print and instead store the errormsg in a
    variable ?

    Thanks,
    Tom
     
    Tom Gur, Dec 17, 2007
    #1
    1. Advertising

  2. Tom Gur

    Paul Lalli Guest

    On Dec 17, 4:07 am, Tom Gur <> wrote:
    > I'm using GetOptions in the following manner:
    > $getoptions_rc = GetOptions( "host=s" => \$host, "port=n" => \$port);
    > Now, in case the user inputs something wrong, like a letter in the
    > port - GetOption prints a default errormsg.
    > how can I suppress the print and instead store the errormsg in a
    > variable ?


    The same way you trap any other warning - by assigning a handler to
    the $SIG{__WARN__} variable:

    perl -MGetopt::Long -le'
    $SIG{__WARN__} = sub { $warn = shift; };
    $getoptions_rc = GetOptions("port=n" => \$port);
    print "GetOptions returned: <<$getoptions_rc>>";
    print "Warning: <<$warn>>" if $warn;
    ' - --port foo

    Result:
    GetOptions returned: <<>>
    Warning: <<Value "foo" invalid for option port (number expected)
    >>



    Note that you might want to do this in a block and local'ly set
    $SIG{__WARN__} so that it resets after the block is over and other
    warnings print to STDERR like normal...

    Paul Lalli
     
    Paul Lalli, Dec 17, 2007
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Moti Shtrobach

    Using GetOptions twice in the script

    Moti Shtrobach, Nov 25, 2003, in forum: Perl Misc
    Replies:
    6
    Views:
    146
    Johan Vromans
    Dec 3, 2003
  2. perl_newbie
    Replies:
    7
    Views:
    186
    A. Sinan Unur
    Jun 2, 2005
  3. GetOptions::Long question

    , Jun 1, 2005, in forum: Perl Misc
    Replies:
    0
    Views:
    85
  4. a
    Replies:
    1
    Views:
    231
    -berlin.de
    Feb 21, 2007
Loading...

Share This Page