9.4. The Apache::File Class

The Perl API includes a class named Apache::File which, when loaded, provides advanced functions for opening and manipulating files at the server side.

Apache::File does two things. First, it provides an object-oriented interface to filehandles similar to Perl's standard IO::File class. While the Apache::File module does not provide all the functionality of IO::File, its methods are approximately twice as fast as the equivalent IO::File methods. Second, when you use Apache::File, it adds several new methods to the Apache class which provide support for handling files under the HTTP/1.1 protocol.

Like IO::File, the main advantage of accessing filehandles through Apache::File 's object-oriented interface is the ability to create new anonymous filehandles without worrying about namespace collision. Furthermore, you don't have to close the filehandle explicitly before exiting the subroutine that uses it; this is done automatically when the filehandle object goes out of scope:

  use Apache::File;
  my $fh = Apache::File->new($config);
  # no need to close

However, Apache::File is still not as fast as Perl's native open( ) and close( ) functions. If you wish to get the highest performance possible, you should use open( ) and close( ) in conjunction with the standard Symbol::gensym or Apache::gensym functions:

{ # using standard Symbol module use Symbol 'gensym'; my $fh = gensym; open $fh, $config; close $fh; } { # Using Apache::gensym() method my $fh = ...

Get Writing Apache Modules with Perl and C now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.