Perl: checking if a value is a float

Articles may may have files attached at the end of the post

While some languages offer an is_float function, Perl seems to only rely on regex.
This tutorial will show how to find if a variable contains an integer or not.

  1. #!/usr/bin/env perl
  2. #
  3. use strict;
  4. use warnings;
  5.  
  6. my @values = ("a", "12.3", 12, "a23");
  7.  
  8. sub isfloat{
  9.   my $val = shift;
  10.   return $val =~ m/^\d+.\d+$/;
  11. }
  12.  
  13. foreach (@values){
  14.   if(isfloat($_)){
  15.       print $_." is a float\n";
  16.   }else{
  17.     print $_." is NOT a float\n";
  18.   }
  19. }

Will output:

$ ./isfloat.pl 
a is NOT a float
12.3 is a float
12 is NOT a float
a23 is NOT a float