Perl Tutorials - Herong's Tutorial Examples - v6.01, by Dr. Herong Yang
CalendarModule.pm - A Sample Perl Module
This section provides a tutorial sample Perl module, CalendarModule.pm, which hold some calendar elements of the current date and time. It also provides a subroutine, isLeapYear().
I think I am ready to write simple modules now. Here is one that provides calendar elements as scalars, and offers one subroutine to determine if the current year is a leap year:
#- CalendarModule.pm #- Copyright (c) HerongYang.com. All Rights Reserved. # package CalendarModule; sub BEGIN { $author = "Dr. Herong Yang"; ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$b) = localtime(); ($swday,$smon,$smday,$stime,$syear) = split(' ',localtime()); } sub isLeapYear { local $day59 = time() - ($yday-59)*24*60*60; local ($0,$1,$2,$3,$m,$5,$6,$7,$8) = localtime($day59); $m = 0 unless $m==1; return $m; } 1;
Here is the testing program:
#- CalendarTest.pl #- Copyright (c) HerongYang.com. All Rights Reserved. # require CalendarModule; print("Date: $CalendarModule::smon"); print(" $CalendarModule::smday"); print(" $CalendarModule::syear\n"); print("Leap year? ",&CalendarModule::isLeapYear(), "\n"); exit;
When running the above Perl script with Perl 5.18 in 2019, I got an error message:
herong> perl CalendarTest.pl Date: Jun 1 2019 Modification of a read-only value attempted at CalendarModule.pm line 12.
But the same script gave me no issue with older versions of Perl. Here is the output I got in 1995:
herong> perl CalendarTest.pl Date: Aug 13 1995 Leap year? 0
The error is caused by my local variables, $0, $1, $2, ..., used in CalendarModule.pm. They are read-only special variables reserved by Perl now. You can replace that statement with the following to avoid the error:
local $m = (localtime($day59))[4];
Table of Contents
Data Types: Values and Variables
Expressions, Operations and Simple Statements
►Name Spaces and Perl Module Files
Including Script Codes from Other Files
do() Function - Including Script Files
require() Function - Including Script Files
"package" Statement - Switching Name Space
BEGIN(), CHECK(), INIT() and END() Functions
►CalendarModule.pm - A Sample Perl Module
Hard References - Addresses of Memory Objects
Objects (or References) and Classes (or Packages)
Typeglob and Importing Identifiers from Other Packages
String Built-in Functions and Performance
File Handles and Data Input/Output
Open Directories and Read File Names
File System Functions and Operations
Socket Communication Over the Internet
XML::Simple Module - XML Parser and Generator
SOAP::Lite - SOAP Server-Client Communication Module
Perl Programs as IIS Server CGI Scripts
CGI (Common Gateway Interface)
XML-RPC - Remote Procedure Call with XML and HTTP
RPC::XML - Perl Implementation of XML-RPC
Integrating Perl with Apache Web Server
CGI.pm Module for Building Web Pages
LWP::UserAgent and Web Site Testing
Converting Perl Script to Executable Binary