in reply to How to check if a scalar value is numeric or string?

The looks_like_number function in Scalar::Util would tell you if Perl thinks your scalar is numeric.

Update: Ok, guess not that, what is your need for this functionality? Strings that look like numbers and numbers are generally interchangeable.

Replies are listed 'Best First'.
Re^2: How to check if a scalar value is numeric or string?
by JavaFan (Canon) on Aug 27, 2009 at 14:58 UTC
    Generally, yes. In a few cases, there's a difference. Binary bit operators, for instance.
    say "12" | "34"; # 36 say 12 | 34; # 46
    And you might think the following code won't give you a divide by zero error:
    if ($num && $num =~ /^[0-9]+$/) {say 1/$num}
    but it will if $num eq '00'.

    Devel::Peek is a tool that can tell you whether scalar holds a numeric value or not (look for the IV and NV flags).

Re^2: How to check if a scalar value is numeric or string?
by bgupta (Novice) on Aug 27, 2009 at 14:58 UTC
    Actually the exact requirement is as below:

    1. Use GetOptions to process the input command line.
    2. Do the required validation. This will result in modifying the command line paramteres
       and resultant will be stored in a hash.
    3. Use this hash in order to form the command line again.
    

    The problem is while doing the 3rd step, I need to distinguish if a given argument is a toggle or a parameter. So, I want to distinguish between 1( toggle ) and '1'( argument ).

      Why don't you save a copy of the command line before calling GetOptions?

      If you can't because you're rearranging the command line somehow, you'll need to pass your reconstructor some of the information you pass to GetOptions (as in, whether a parameter is a toggle or takes a value).

        Since I am modifying the resultant hash drastically, it is very difficult to keep track of the changes in the hash.

      Your requirement mentions GetOptions. Does this mean you are using Getopt::Long? If so, how are you specifying the option? opt=s, opt:s, opt=i, opt:i, opt, etc?

      Getopt::Long is usually good about setting sane values. If you asked for an integer with :i, it will set your value to 0 if there was no argument given, so you can test with exists to see if it was set.

      $,=' ';$\=',';$_=[qw,Just another Perl hacker,];print@$_;

      If you know at the point where you store the value that it is a 1 or a '1', then store '1' (including the quote marks) for the string version.


      True laziness is hard work