Determine if a value is numeric in perl script

209 views Asked by At

My perl script takes the first command line argument and sets '$numlines' to it. Then I have an if statement that is supposed to determine if numlines is numeric (I want to use this value later if it is numeric) but even when I input a numeric value as my first command line argument, my script always skips the if statement anyways.

My code:

my $line;
my $counter = 0;
my @list;
my $numlines = shift @ARGV;
if ( $numlines !~ (/^-?\d+$/) ) {
    print "First argument is a number\n";
    while ($line=<>) {
        push(@list, $line);
    }
    @list = reverse @list;
    foreach (@list) {
       if ( $counter == $numlines ) {
          last;
       }
       print "$_";
       $counter++;
    }
    exit 0;
}

1

There are 1 answers

0
choroba On BEST ANSWER

The condition should be the other way round.

if ($numlines =~ /^-?\d+$/)