>>>>>>>>>>>> Original Message <<<<<<<<<<<<<<<<<<
On 19.06.01, 10:38:32, Jan.Trippler@t-online.de (Jan Trippler) wrote regarding re ot perl variablen-unterscheidung@3:
On Die, Jun 19, 2001 at 09:18:03 +0200, Stefan Troeger wrote:
On Tue, Jun 19 2001 at 07:18 +0200, Oliver Kiehl wrote:
On 19-Jun-2001, Duck (Marco Wenzel) wrote:
Mein Freund sucht eine Möglichkeit in Perl zu unterscheiden, ob eine Variable einen Zahlenwert oder ein Wort enthält.
if ($variable =~ /\d+/) { print $variable, "is eine Zahl\n"; } elsif ($variable =~ /\w+/) { print $variable "ist ein Wort\n"; }
Damit wird jeder String, in dem mindestens eine Ziffer vorkommt, als Zahl erkannt, z.B. auch "a1b". Falls die Zahlen keine Kommas, Punkte oder Vorzeichen enthalten, wäre
if ($variable =~ /^\d+$/)
sinnvoll.
$is_num = ( $variable =~ /^\d*[.,]?\d+$/ );
berücksichtigt auch Punkt und Komma.
Found in usr/lib/perl5/5.6.0/pod/perlfaq4.pod How do I determine whether a scalar is a number/whole/integer/float? Assuming that you don't care about IEEE notations like "NaN" or "Infinity", you probably just want to use a regular expression. if (/\D/) { print "has nondigits\n" } if (/^\d+$/) { print "is a whole number\n" } if (/^-?\d+$/) { print "is an integer\n" } if (/^[+-]?\d+$/) { print "is a +/- integer\n" } if (/^-?\d+\.?\d*$/) { print "is a real number\n" } if (/^-?(?:\d+(?:\.\d*)?|\.\d+)$/) { print "is a decimal number" } if (/^([+-]?)(?=\d|\.\d)\d*(\.\d*)?([Ee]([+-]?\d+))?$/) { print "a C float" } If you're on a POSIX system, Perl's supports the `POSIX::strtod' function. Its semantics are somewhat cumbersome, so here's a `getnum' wrapper function for more convenient access. This function takes a string and returns the number it found, or `undef' for input that isn't a C float. The `is_numeric' function is a front end to `getnum' if you just want to say, ``Is this a float?'' sub getnum { use POSIX qw(strtod); my $str = shift; $str =~ s/^\s+//; $str =~ s/\s+$//; $! = 0; my($num, $unparsed) = strtod($str); if (($str eq '') || ($unparsed != 0) || $!) { return undef; } else { return $num; } } sub is_numeric { defined getnum($_[0]) } Or you could check out the String::Scanf module on CPAN instead. The POSIX module (part of the standard Perl distribution) provides the `strtol' and `strtod' for converting strings to double and longs, respectively. Greets Florian