Why the numbers are not resolved in IF condition in Perl without quotes

Viewed 48

I have a script which will do certain set of operation based on the time in IF condition. So basically IF will look for the Current Time which is Hour and Minutes.

Here is the script:

use strict;
use warnings;

my $TIME = `date '+%H%M'`;
chomp $TIME;

print $TIME."\n";

if (( $TIME > 0100) && ($TIME < 0300)){
        print "1st IF\n";
} elsif (( $TIME > 0300) && ($TIME < 0500)){
        print "2nd IF\n";
} else {
        print "Default IF\n";
}

Lets say now the time is 0130 and it suppose to print 1st IF. But its printing Default IF. Similarly when the time is 0430 and it suppose to print 2nd IF. But its printing Default IF.

But when I enclose the time value in double quotes "" it works. Like below -

if (( $TIME > "0100") && ($TIME < "0300")){

Do the $TIME is resolving as a string ? I was thinking the $TIME would have numbers and it doesn't require quotes.

2 Answers

As you can find in perlnumber, literal numbers starting with zeros are interpreted as octal numbers. 0100 is therefore 64 and 0300 is 192.

When numifying a string, leading zeros are ignored.

See also Time::Piece on how to handle time in Perl without the need to shell out.

use Time::Piece;
my $time = localtime->strftime('%H%M');

Time::Piece has been a standard part of the Perl distribution since Perl 5.10 (in 2002). If you use the right tool for the job, then things get a lot easier :-)

use Time::Piece;

my $hour = localtime->hour;

if ($hour > 1 and $hour < 3) {
  # do something
} elsif ($hour > 3 and $hour < 5) {
  # do something else
} else {
  # do the default thing
}

Update: You don't even need to use Time::Piece. You can get the hour from localtime() easily enough.

my $hour = (localtime)[2];

# The rest of the code is the same as my previous example
Related