Home > Enterprise >  Determine if a value is numeric in perl script
Determine if a value is numeric in perl script

Time:03-07

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;
}

CodePudding user response:

The condition should be the other way round.

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