Home > Articles > Web Development > Perl

📄 Contents

  1. Input/Output Basics
  2. Networking Made Easy
  3. Filehandles
  4. Using Object-Oriented Syntax with the IO::Handle and IO::File Modules
  5. Summary

Using Object-Oriented Syntax with the IO::Handle and IO::File Modules

We use Perl5's object-oriented facilities extensively later in this book. Although you won't need to know much about creating object-oriented modules, you will need a basic understanding of how to use OO modules and their syntax. This section illustrates the basics of Perl's OO syntax with reference to the IO:Handle and IO::File module, which together form the basis of Perl's object-oriented I/O facilities.

Objects and References

In Perl, references are pointers to data structures. You can create a reference to an existing data structure using the backslash operator. For example:

$a = 'hi there'; 
$a_ref = \$a; # reference to a scalar
@b = ('this','is','an','array');
$b_ref = \@b; # reference to an array
%c = ( first_name => 'Fred', last_name => 'Jones');
$c_ref = \%c; # reference to a hash

Once a reference has been created, you can make copies of it, as you would any regular scalar, or stuff it into arrays or hashes. When you want to get to the data contained inside a reference, you dereference it using the prefix appropriate for its contents:

$a = $$a_ref;
@b = @$b_ref;
%c = %$c_ref;

You can index into array and hash references without dereferencing the whole thing by using the -> syntax:

$b_ref->[2];   # yields "an"
$c_ref->{last_name};  # yields "Jones"

It is also possible to create references to anonymous, unnamed arrays and hashes, using the following syntax:

$anonymous_array = ['this','is','an','anonymous','array'];
$anonymous_hash = { first_name => 'Jane', last_name => 'Doe' };

If you try to print out a reference, you'll get a string like HASH(0x82ab0e0), which indicates the type of reference and the memory location where it can be found (which is just short of useless).

An object is a reference with just a little bit extra. It is "blessed" into a particular module's package in such a way that it carries information about what module created it.2 The blessed reference will continue to work just like other references. For example, if the object named $object is a blessed hash reference, you can index into it like this:

$object->{last_name};

What makes objects different from plain references is that they have methods. A method call uses the -> notation, but followed by a subroutine name and optional subroutine-style arguments:

$object->print_record(); # invoke the print_record() method

You may sometimes see a method called with arguments, like this:

$object->print_record(encoding => 'EBCDIC');

The "=>" symbol is accepted by Perl as a synonym for ','. It makes the relationship between the two arguments more distinct, and has the added virtue of automatically quoting the argument on the left. This allows us to write encoding rather than "encoding". If a method takes no arguments, it's often written with the parentheses omitted, as in:

$object->print_record;

In many cases, print_record() will be a subroutine defined in the object's package. Assuming that the object was created by a module named BigDatabase, the above is just a fancy way of saying this:

BigDatabase::print_record($object);

However, Perl is more subtle than this, and the print_record(), method definition might actually reside in another module, which the current module inherits from. How this works is beyond the scope of this introduction, and can be found in the perltoot, perlobj, and perlref POD pages, as well as in [Wall 2000] and the other general Perl reference works listed in Appendix D.

To create an object, you must invoke one of its constructors. A constructor is a method call that is invoked from the module's name. For example, to create a new BigDatabase object:

$object = BigDatabase->new(); # call the new() constructor

Constructors, which are a special case of a class method, are frequently named new(). However, any subroutine name is possible. Again, this syntax is part trickery. In most cases an equivalent call would be:

$object = BigDatabase::new('BigDatabase');

This is not quite the same thing, however, because class methods can also be inherited.

The IO::Handle and IO::File Modules

The IO::Handle and IO::File modules, standard components of Perl, together provide object-oriented interface to filehandles. IO::Handle provides generic methods that are shared by all filehandle objects, including pipes and sockets. The more specialized class, IO::File, adds functionality for opening and manipulating files. Together, these classes smooth out some of the bumps and irregularities in Perl's built-in filehandles, and make larger programs easier to understand and maintain.

IO::File's elegance does not by itself provide any very compelling reason to choose the object-oriented syntax over native filehandles. Its main significance is that IO::Socket, IO::Pipe, and other I/O-related modules also inherit their behavior from IO::Handle. This means that programs that read and write from local files and those that read and write to remote network servers share a common, easy-to-use interface.

We'll get a feel for the module by looking at a tiny example of a program that opens a file, counts the number of lines, and reports its findings (Figure 1.4).

Figure 1.4
The count_lines.pl program

    Lines 1–3: Load modules  We turn on strict syntax checking, and load the IO::File module.

    Lines 4–5: Initialize variables  We recover from the command line the name of the file to perform the line count on, and initialize the $counter variable to zero.

    Line 6: Create a new IO::File object  We call the IO::File::new() method, using the syntax IO::File->new(). The argument is the name of the file to open. If successful, new() returns a new IO::File object that we can use for I/O. Otherwise it returns undef, and we die with an error message.

    Lines 7–9: Main loop  We call the IO::File object's getline() method in the test portion of a while() loop. This method returns the next line of text, or undef on end of file—just like <>.

    Each time through the loop we bump up $counter. The loop continues until getline() returns undef.

    Line 10: Print results  We print out our results by calling STDOUT->print(). We'll discuss why this surprising syntax works in a moment.

When I ran count_lines.pl on the unfinished manuscript for this chapter, I got the following result:

% count_lines.pl ch1.pod
Counted 2428 lines

IO::File objects are actually blessed typeglob references (see the Passing and Storing Filehandles section earlier in this chapter). This means that you can use them in an object-oriented fashion, as in:

$fh->print("Function calls are for the birds.\n");

or with the familiar built-in function calls:

print $fh "Object methods are too effete.\n";

Many of IO::File's methods are simple wrappers around Perl's built-in functions. In addition to print() and getline() methods, there are read(), syswrite(), and close() methods, among others. We discuss the pros and cons of using object-oriented method calls and function calls in Chapter 5, where we introduce IO::Socket.

When you load IO::File (technically, when IO::File loads IO::Handle, which it inherits from), it adds methods to ordinary filehandles. This means that any of the methods in IO::File can also be used with STDIN, STDOUT, STDERR, or even with any conventional filehandles that you happen to create. This is why line 10 of Figure 1.4 allows us to print to standard output by calling STDOUT->print().

Of the method listings that follow, only the new() and new_tmpfile()i methods are actually defined by IO::File. The rest are inherited from IO::Handle and can be used with other descendents of IO::Handle, such as IO::Socket. This list is not complete. I've omitted some of the more obscure methods, including those that allow you to move around inside a file in a record-oriented fashion, because we won't need them for network communications.


$fh = IO::File->new($filename [,$mode [,$perms]])

The new() method is the main constructor for IO::File. It is a unified replacement for both open() and sysopen(). Called with a single argument, new() acts like the two-argument form of open(), taking a filename optionally preceded by a mode string. For example, this will open the indicated file for appending:

$fh = IO::File->new(">darkstar.txt");
If called with two or three arguments, IO::File treats the second argument as the open mode, and the third argument as the file creation permissions. $mode may be a Perl-style mode string, such as "+<", or an octal numeric mode, such as those used by sysopen(). As a convenience, IO::File automatically imports the Fcntl O_* constants when it loads. In addition, open() allows for an alternative type of symbolic mode string that is used in the C fopen() call; for example, it allows "w" to open the file for writing. We won't discuss those modes further here, because they do not add functionality.

The permission agreement given by $perms is an octal number, and has the same significance as the corresponding parameter passed to sysopen().

If new() cannot open the indicated file, it will return undef and set $! to the appropriate system error message.

$fh = IO::File->new_tmpfile

The new_tmpfile() constructor, which is called without arguments, creates a temporary file opened for reading and writing. On UNIX systems, this file is anonymous, meaning that it cannot be seen on the file system. When the IO::File object is destroyed, the file and all its contents will be deleted automatically.

This constructor is useful for storing large amounts of temporary data.

$result = $fh->close

The close() method closes the IO::File object, returning a true result if successful. If you do not call close() explicitly, it will be called automatically when the object is destroyed. This happens when the script exits, if you happen to undef() the object, or if the object goes out of scope such as when a my variable reaches the end of its enclosing block.

$result = $fh->open($filename [,$mode [,$perms]])

You can reopen a filehandle object on the indicated file by using its open() method. The input arguments are identical to new(). The method result indicates whether the open was successful.

This is chiefly used for reopening the standard filehandles STDOUT, STDIN, and STDERR. For example:

STDOUT->open(">log.txt") or die "Can't reopen STDOUT: $!";
Calls to print() will now write to the file log.txt.

$result = $fh->print(@args) $result = $fh->printf($fmt,@args) $bytes = $fh->write($data [,$length [,$offset]]) $bytes = $fh->syswrite($data [,$length [,$offset]])

The print(), printf(), and syswrite() methods work exactly like their built-in counterparts. For example, print() takes a list of data items, writes them to the filehandle object, and returns true if successful.

The write() method is the opposite of read(), writing a stream of bytes to the filehandle object and returning the number successfully written. It is similar to syswrite(), except that it uses stdio buffering. This method corrects the inconsistent naming of the built-in write() function, which creates formatted reports. The IO::File object method that corresponds to the built-in write() goes by the name of format_write().

$line = $fh->getline @lines = $fh->getlines $bytes = $fh->read($buffer,$length [,$offset]) $bytes = $fh->sysread($buffer,$length [,$offset])

The getline() and getlines() methods together replace the <> operator. getline() reads one line from the filehandle object and returns it, behaving in the same way in both scalar and list contexts. The getlines() method acts like <> in a list context, returning a list of all the available lines. getline() will return undef at the end of file.

The read() and sysread() methods act just like their built-in function counterparts.

$previous = $fh->autoflush([$boolean])

The autoflush() method gets or sets the autoflush() mode for the filehandle object. Called without arguments, it turns on autoflush. Called with a single boolean argument, it sets autoflush to the indicated status. In either case, autoflush()i returns the previous value of the autoflush state.

$boolean = $fh->opened

The opened() method returns true if the filehandle object is currently valid. It is equivalent to:

defined fileno($fh);
$boolean = $fh->eof

Returns true if the next read on the filehandle object will return EOF.

$fh->flush

The flush() method immediately flushes any data that is buffered in the filehandle object. If the filehandle is being used for writing, then its buffered data is written to disk (or to the pipe, or network, as we'll see when we get to IO::Socket objects). If the filehandle is being used for reading, any data in the buffer is discarded, forcing the next read to come from disk.

$boolean = $fh->blocking([$boolean])

The blocking() method turns on and off blocking mode for the filehandle. We discuss how to use this at length in Chapter 13.

$fh->clearerr $boolean = $fh->error

These two methods are handy if you wish to perform a series of I/O operations and check the error status only after you're finished. The error()i method will return true if any errors have occurred on the filehandle since it was created, or since the last call to clearerr(). The clearerr() method clears this flag.


In addition to the methods listed here, IO::File has a constructor named new_from_fd(), and a method named fdopen(), both inherited from IO::Handle. These methods can be used to save and restore objects in much the way that the >&FILEHANDLE does with standard filehandles.


$fh = IO::File->new_from_fd($fd,$mode)

The new_from_fd() method opens up a copy of the filehandle object indicated by $fd using the read/write mode given by $mode. The object may be an IO::Handle object, an IO::File object, a regular filehandle, or a numeric file descriptor returned by fileno(). $mode must match the mode with which $fd was originally opened. For example:

$saveout = IO::File->new_from_fd(STDOUT,">");

$result = $fh->fdopen($fd,$mode)

The fdopen() method is used to reopen an existing filehandle object, making it a copy of another one. The $fd argument may be an IO::Handle object or a regular filehandle, or a numeric file descriptor $mode must match the mode with which $fd was originally opened.

This is typically used in conjunction with new_from_fd() to restore a saved filehandle:

$saveout = IO::File->new_from_fd(STDOUT,">"); # save STDOUT
STDOUT->open('>log.txt');           # reopen on a file
STDOUT->print("Yippy yie yay!\n");      # print something
STDOUT->fdopen($saveout,">");         # reopen on saved value

See the POD documentation for IO::Handle and IO::File for information about the more obscure features that these modules provide.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020