My program is supposed to decide whether a number is an integer or not.

I've tried:
if (\$variable % 1 = 0)
and:
if (\$variable % 1.0 = 0)

I know that it can be done with regular expressions, but I'm only on day three of Sams Perl in 21 Days and I haven't learned them yet.

Is there another way?

## All 3 Replies

Here is some code from The Perl Cookbook from O'Reilly & Associates, which is where I get the best examples for Perl coding:

``````You must decide what you will and will not accept. Then, construct a regular expression to match those
things alone.
Compare it against a regular expression that matches the kinds of numbers you're interested in.
if (\$string =~ /PATTERN/) {
# is a number
} else {
# is not
}
Here are some precooked solutions (the cookbook's equivalent of just-add-water meals) for
most common cases.
warn "has nondigits" if /\D/;
warn "not a natural number" unless /^\d+\$/; # rejects -3
warn "not an integer" unless /^-?\d+\$/; # rejects +3
warn "not an integer" unless /^[+-]?\d+\$/;
warn "not a decimal number" unless /^-?\d+\.?\d*\$/; # rejects .2
warn "not a decimal number" unless /^-?(?:\d+(?:\.\d*)?|\.\d+)\$/;
warn "not a C float"
unless /^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?\$/;
``````

Isn't that still regex?

Hi Killingmonk,

Is there another way?

Yes! There is more than one way to do it!

Using the method looks_like_number in the core module Scalar::Util, you can get want you want without using regex.

You can read the documentation of this module from the CLI like so:
`perldoc Scalar::Util`

Using it like so:

using perl one liner on windows Example 1

`perl -MScalar::Util -we "print Scalar::Util::looks_like_number \$ARGV[0] ? q/true/ : q/false/" 4.0 #prints true`

using perl one liner on windows Example 2

`perl -MScalar::Util -we "print Scalar::Util::looks_like_number \$ARGV[0] ? q/true/ : q/false/" 4.O #prints false`

You probably what to check how to use perl on command line interface, do `perldoc perlrun` to see the use of `-M` and others. Of course, if you are using other OS, you may want to use single quote instead of double as use on windows.

Lastly, are you sure the book you are using is not dated already? In as much as you can still get some wisdom on Perl old books, I still use some of them. There is need for you to check more recents books, which teaches Modern Perl.

You can also do `perldoc perlintro` from your CLI all given to you for free...

Hope this helps!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.