POSIX
The POSIX module brings in many standard C-style math and time functions.
In this page:
POSIX
POSIX provides floor and ceil for rounding down and up, fmod for floating-point remainders, and strftime for formatting dates and times. It also defines constants such as INT_MAX and DBL_MAX. Importing everything by default is noisy, so ask for only the names you want.
Note:
Perl's built-in int truncates toward zero, while POSIX floor always rounds toward negative infinity.
Example: POSIX
use strict;
use warnings;
use POSIX qw(floor ceil fmod strftime INT_MAX);
print "floor(3.7)=", floor(3.7), " ceil(3.2)=", ceil(3.2), "\n";
print "floor(-3.7)=", floor(-3.7), " int(-3.7)=", int(-3.7), "\n";
print "fmod(10.5, 3)=", fmod(10.5, 3), "\n";
print "INT_MAX=", INT_MAX, "\n";
print "epoch start: ", strftime("%Y-%m-%d %H:%M:%S", gmtime(0)), "\n";
print "a fixed moment: ", strftime("%A, %d %B %Y", gmtime(86400 * 365)), "\n";
printf "rounded: %d\n", floor(2.5 + 0.5);
# Output:
# floor(3.7)=3 ceil(3.2)=4
# floor(-3.7)=-4 int(-3.7)=-3
# fmod(10.5, 3)=1.5
# INT_MAX=2147483647
# epoch start: 1970-01-01 00:00:00
# a fixed moment: Friday, 01 January 1971
# rounded: 3
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Importing all of POSIX and clobbering built-in names
- Expecting int to round negative numbers down
- Passing local time to strftime and getting different output on different machines
Chapter Summary
- floor and ceil round down and up
- fmod gives a floating-point remainder
- strftime formats time values
- Import only the names you need
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: