← Back to Perl Course | Chapter 8: Modules | Lesson 5 of 7

POSIX

The POSIX module brings in many standard C-style math and time functions.

In this page:

  1. POSIX

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

perl
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
Common Mistakes
  1. Importing all of POSIX and clobbering built-in names
  2. Expecting int to round negative numbers down
  3. 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.