Search code examples
regexperlif-statementnumbersint

How do I know if there is a number in my list?


My code looks like this:

#!/usr/bin/perl
$counter=0;
@list=<STDIN>;
chomp(@list);
if (@list==~ /^[+-]?\d+$/ )
{
$counter++;
}
print $counter;

So I write datas like: a b c d 1 2 And then it should print 2

beacuse of the 1,2

But it does not matter what datas i write into the list i get back 0. So what is the problem with my if?


Solution

  • Always use strict; use warnings;. If your goal is to count the number of digit elements in your list, you can use grep to filter the list elements, then apply scalar to get its length (or use $length directly instead of storing the filtered list in @matches):

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my @list = <STDIN>;
    chomp(@list);
    my @matches = grep /^[+-]?\d+$/, @list;
    print scalar @matches . "\n";
    

    Sample run:

    $ ./count.pl
    -62
    a
    b
    4
    c
    +91023
    d
    3