On 29 Jul., 17:40, [EMAIL PROTECTED] (Paul Lalli) wrote:
> 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 
> athttp://search.cpan.org/~abigail/Regexp-Common-2.122/lib/Regexp/Common...

I don't know why my first answers weren't published, but I will try
again. First of all thank you for your detailed answer. In my case I
only need to reed a number like 1.2345, so simply excluding [a-zA-Z]
is fine for me...

> > 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

Let's say I have a string like this:
-----------------
Butter (kg)           2.00052                      Peanuts
(kg)                5.35
-----------------

Ho do I extract just the number(s) from that string and put them in a
variable? Is there a beautiful way to do it?

Once again, thank you very much for your help!

Jan-Henrik


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


Reply via email to