On Jul 29, 8:46 am, [EMAIL PROTECTED] (Jan-Henrik) wrote:
> I'm new to Perl and I have a simple question:

Yes, but unfortunately it doesn't have a simple answer.... :-/

> I ask for the entry of a number vie <STDIN>:
>
> ----------------------------------------
> #!/usr/bin/perl -w
> use strict;
>
> my $foo;
> print "Enter number: ";
> $foo = <STDIN>;
> comp($foo);

I think you meant "chomp", not "comp".

> ----------------------------------------
>
> Now I would like to check wether the user really entered a number and
> not letters. What would a check like that look like? A regular
> expression like this:
> ----------------------------------------
> unless ($foo =~ /[a-zA-Z\D+][^.][\D*]/ {...};
> ----------------------------------------
>
> Is there an easier or more beautiful way?

Well the problem is that you need to define what you mean by "a
number".   Depending on what kinds of numbers are valid, your regexp
might be simple or very complex:

A single digit:   /^\d$/
A whole number:  /^\d+$/
An integer, possibly negative:   /^-?\d+$/
A floating point number, possibly negative:  /^-?\d+\.\d+$/
An integer *or* floating point number, possibly negative:  /^-?\d+(?:\.
\d+)?$/
A number in scientific notation:  /^-?\d+(?:\.\d+)?(?:[eE]-?\d+(?:\.\d
+)?)?$/

There are more complications that could be thrown in too.  Like, is a
+ sign allowed for positive numbers?  Do floating points that are less
than 0 have to start with 0, or can just ".9" be a valid number?  Can
they use the comma to separate thousands?

Depending on what you're looking for, you might be better off using
the Regexp::Common::number module, found on the CPAN at
http://search.cpan.org/~abigail/Regexp-Common-2.122/lib/Regexp/Common/number.pm

> Also, how would I substract just a number from a string? Searched the
> net for an example but didn't succeed, so sorry for asking a question
> like that...

I don't know what you're trying to ask here.  Please give us an
example of what you want to do - what the string will contain before
you do something to it, and what the string will look like afterwards.

Good luck,
Paul Lalli


--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to