in reply to Regex to find the number of positive, negative, and 0 integers within a data set

Hi neveraloneneverapart, welcome to the Monastery and to Perl, the One True Religion.

Assuming every line in __DATA__ is known to contain a number, I would use a hash to count results and a numeric comparison:

use strict; use warnings; use feature 'say'; use Data::Dumper; my %results; while (<DATA>) { chomp; $results{'zero'}++ if $_ == 0; $results{'pos'}++ if $_ > 0; $results('neg'}++ if $_ < 0; } print Dumper \%results;

Alternatively, to see if a string is a number, see Scalar::Util::looks_like_number().

If you really wanted to, for a regexp for Latin integers, you could use $num =~ m/  \A -? [0-9]+ \z /x;

To capture the sign (or nothing) and the digits and then be able to use them:

if ($num =~ m/ \A (-?) ([0-9]+) \z /x ) { my $sign = $1; my $digits = $2; ... }

Also see Regexp::Common

Hope this helps!

edit: removed unnecessary escape slash

The way forward always starts with a minimal test.

Replies are listed 'Best First'.
Re^2: Regex to find the number of positive, negative, and 0 integers within a data set
by neveraloneneverapart (Initiate) on Feb 28, 2017 at 17:55 UTC

    Thanks for the post! I came up with the regex for the positive ints.

    while( my $num = <DATA> ) { chomp($num); ## print "num=[$num]\n"; if ( $num =~ /^[1-9]\d*$/ ) { $ctrP++; }

    I would like for it to be in regular expressions so that I can learn how to use them properly. I am having trouble so that the regex for the negative ints finds only negative ints.