Anonymous Monk has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,

I'm very puzzled. I am simply reading files of numbers, seperating them into arrays and testing the numbers in the arrays to see if they're numeric.

My print statement shows neither array have any numerbers in them!

while (<INPUT>) { my $line = $_; my @file; push @file, $_; # the numbers are floating point if ($line =~ /^(\d+\s+)(\d+\W?\s+)(\d+\W?\s+)/) { push @nums, $2 if $2 =~ /\d+/; push @nums2, $3 if $3 =~ /\d+/; } } my ($i, $j); print "$i\t $j\n";
Data is a bit like this:
0.2360 0.3789 0.1879 0.3924 0.234 0.172 0.505 0 +.2605 0.3992 0.1560 0.4158 0.284 0.142 0.502 0.2662 0.3377 + 0.2025 0.4286 0.214 0.081 0.452

Replies are listed 'Best First'.
Re: Why are my numbers not numeric???
by Abigail-II (Bishop) on Oct 09, 2003 at 16:12 UTC
    The beginning of your regex is: /^(\d+\s+)/, which says: match the beginning of the string, then some digits, then whitespace. But your string starts with a digit, then a dot.

    Abigail

      so does this mean that I can't pattern match numbers in a string like this - I should start out saving them all in an array? thanks!
        Uhm, no, that doesn't mean it. \d+ matches a string of digits. If you want to match different type of numbers (decimal numbers, integers, reals, etc), you need different regexes. See the FAQ, or Regexp::Common.

        Abigail

Re: Why are my numbers not numeric???
by thens (Scribe) on Oct 09, 2003 at 16:16 UTC
    while (<INPUT>) { my $line = $_; my @file; push @file, $_; <snip>

    You have declared the array @file inside the while loop which means the scope of it is limited to the body of the loop. Everytime perl will create a variable called @file and then push the line into it, only to throw it away at the end of that iteration. Coping with Scoping is an excellent reference to understand the scope of the variables.

    use Regex::Common to parse common entities like Number, date etc.

    -T

    use perl;use strict;

Re: Why are my numbers not numeric???
by bbfu (Curate) on Oct 09, 2003 at 21:51 UTC

    The only time you actually print anything is when you do this:

    my ($i, $j); print "$i\t $j\n";

    $i and $j don't contain anything. What were you expecting to print, then?

    Perhaps, after following the advice given by Abigail-II and thens, you mean to say:

    print scalar(@nums), "\t", scalar(@nums2), "\n";

    bbfu
    Black flowers blossom
    Fearless on my breath