Seth Woolley's Man Viewer

perlopentut(1) - perlopentut - tutorial on opening things in Perl - man 1 perlopentut

([section] manual, -k keyword, -K [section] search, -f whatis)
man plain no title

PERLOPENTUT(1)         Perl Programmers Reference Guide         PERLOPENTUT(1)

       perlopentut - tutorial on opening things in(1,8) Perl

       Perl has two simple, built-in ways to open(2,3,n) files: the shell way for
       convenience, and the C way for precision.  The shell way also has 2-
       and 3-argument forms, which have different semantics for handling the
       filename.  The choice is yours.

Open A la shell
       Perl's "open(2,3,n)" function was designed to mimic the way command-line redi-
       rection in(1,8) the shell works.  Here are some basic examples from the

           $ myprogram file1 file2 file3
           $ myprogram    <  inputfile
           $ myprogram    >  outputfile
           $ myprogram    >> outputfile
           $ myprogram    |  otherprogram
           $ otherprogram |  myprogram

       And here are some more advanced examples:

           $ otherprogram      | myprogram f1 - f2
           $ otherprogram 2>&1 | myprogram -
           $ myprogram     <&3
           $ myprogram     >&4

       Programmers accustomed to constructs like those above can take comfort
       in(1,8) learning that Perl directly supports these familiar constructs using
       virtually the same syntax as the shell.

       Simple Opens

       The "open(2,3,n)" function takes two arguments: the first is a filehandle, and
       the second is a single string(3,n) comprising both what to open(2,3,n) and how to
       open(2,3,n) it.  "open(2,3,n)" returns true when it works, and when it fails, returns
       a false value and sets the special variable $! to reflect the system
       error.  If the filehandle was previously opened, it will be implicitly
       closed first.

       For example:

           open(2,3,n)(INFO,      "datafile") || die("can't open(2,3,n) datafile: $!");
           open(2,3,n)(INFO,   "<  datafile") || die("can't open(2,3,n) datafile: $!");
           open(2,3,n)(RESULTS,">  runstats") || die("can't open(2,3,n) runstats: $!");
           open(2,3,n)(LOG,    ">> logfile ") || die("can't open(2,3,n) logfile:  $!");

       If you prefer the low-punctuation version(1,3,5), you could write(1,2) that this

           open(2,3,n) INFO,   "<  datafile"  or die "can't open(2,3,n) datafile: $!";
           open(2,3,n) RESULTS,">  runstats"  or die "can't open(2,3,n) runstats: $!";
           open(2,3,n) LOG,    ">> logfile "  or die "can't open(2,3,n) logfile:  $!";

       A few things to notice.  First, the leading less-than is optional.  If
       omitted, Perl assumes that you want to open(2,3,n) the file(1,n) for reading.

       Note also that the first example uses the "||" logical operator, and
       the second uses "or", which has lower precedence.  Using "||" in(1,8) the
       latter examples would effectively mean

           open(2,3,n) INFO, ( "<  datafile"  || die "can't open(2,3,n) datafile: $!" );

       which is definitely not what you want.

       The other important thing to notice is that, just as in(1,8) the shell, any
       white space before or after the filename is ignored.  This is good,
       because you wouldn't want these to do different things:

           open(2,3,n) INFO,   "<datafile"
           open(2,3,n) INFO,   "< datafile"
           open(2,3,n) INFO,   "<  datafile"

       Ignoring surrounding whitespace also helps for when you read(2,n,1 builtins) a filename
       in(1,8) from a different file(1,n), and forget to trim it before opening:

           $filename = <INFO>;         # oops, \n still there
           open(2,3,n)(EXTRA, "< $filename") || die "can't open(2,3,n) $filename: $!";

       This is not a bug, but a feature.  Because "open(2,3,n)" mimics the shell in(1,8)
       its style of using redirection arrows to specify how to open(2,3,n) the file(1,n),
       it also does so with respect to extra white space around the filename
       itself as well.  For accessing files with naughty names, see "Dis-
       pelling the Dweomer".

       There is also a 3-argument version(1,3,5) of "open(2,3,n)", which lets you put the
       special redirection characters into their own argument:

           open(2,3,n)( INFO, ">", $datafile ) || die "Can't create $datafile: $!";

       In this case, the filename to open(2,3,n) is the actual string(3,n) in(1,8) $datafile,
       so you don't have to worry about $datafile containing characters that
       might influence the open(2,3,n) mode, or whitespace at the beginning of the
       filename that would be absorbed in(1,8) the 2-argument version.  Also, any
       reduction of unnecessary string(3,n) interpolation is a good thing.

       Indirect Filehandles

       "open(2,3,n)"'s first argument can be a reference to a filehandle.  As of perl
       5.6.0, if(3,n) the argument is uninitialized, Perl will automatically create
       a filehandle and put a reference to it in(1,8) the first argument, like so:

           open(2,3,n)( my $in(1,8), $infile )   or die "Couldn't read(2,n,1 builtins) $infile: $!";
           while ( <$in(1,8)> ) {
               # do something with $_
           close(2,7,n) $in(1,8);

       Indirect filehandles make namespace management easier.  Since filehan-
       dles are global to the current package, two subroutines trying to open(2,3,n)
       "INFILE" will clash.  With two functions opening indirect filehandles
       like "my $infile", there's no clash and no need to worry about future

       Another convenient behavior is that an indirect filehandle automati-
       cally closes when it goes out of scope or when you undefine it:

           sub firstline {
               open(2,3,n)( my $in(1,8), shift ) && return scalar <$in(1,8)>;
               # no close(2,7,n)() required

       Pipe Opens

       In C, when you want to open(2,3,n) a file(1,n) using the standard I/O library, you
       use the "fopen" function, but when opening a pipe(2,8), you use the "popen"
       function.  But in(1,8) the shell, you just use a different redirection char-
       acter.  That's also the case for Perl.  The "open(2,3,n)" call remains the
       same--just its argument differs.

       If the leading character is a pipe(2,8) symbol, "open(2,3,n)" starts up a new com-
       mand and opens a write-only filehandle leading into that command.  This
       lets you write(1,2) into that handle and have what you write(1,2) show up on that
       command's standard input.  For example:

           open(2,3,n)(PRINTER, "| lpr -Plp1")    || die "can't run lpr: $!";
           print PRINTER "stuff\n";
           close(2,7,n)(PRINTER)                  || die "can't close(2,7,n) lpr: $!";

       If the trailing character is a pipe(2,8), you start up a new command and
       open(2,3,n) a read-only filehandle leading out of that command.  This lets
       whatever that command writes to its standard output show up on your
       handle for reading.  For example:

           open(2,3,n)(NET, "netstat -i -n |")    || die "can't fork netstat: $!";
           while (<NET>) { }               # do something with input
           close(2,7,n)(NET)                      || die "can't close(2,7,n) netstat: $!";

       What happens if(3,n) you try to open(2,3,n) a pipe(2,8) to or from a non-existent com-
       mand?  If possible, Perl will detect the failure and set(7,n,1 builtins) $! as usual.
       But if(3,n) the command contains special shell characters, such as ">" or
       "*", called 'metacharacters', Perl does not execute the command
       directly.  Instead, Perl runs the shell, which then tries to run the
       command.  This means that it's the shell that gets(3,n) the error(8,n) indica-
       tion.  In such a case, the "open(2,3,n)" call will only indicate failure if(3,n)
       Perl can't even run the shell.  See "How can I capture STDERR from an
       external command?" in(1,8) perlfaq8 to see how to cope with this.  There's
       also an explanation in(1,8) perlipc.

       If you would like to open(2,3,n) a bidirectional pipe(2,8), the IPC::Open2 library
       will handle this for you.  Check out "Bidirectional Communication with
       Another Process" in(1,8) perlipc

       The Minus File

       Again following the lead of the standard shell utilities, Perl's "open(2,3,n)"
       function treats a file(1,n) whose name is a single minus, "-", in(1,8) a special
       way.  If you open(2,3,n) minus for reading, it really means to access(2,5) the
       standard input.  If you open(2,3,n) minus for writing, it really means to
       access(2,5) the standard output.

       If minus can be used as the default input or default output, what hap-
       pens if(3,n) you open(2,3,n) a pipe(2,8) into or out of minus?  What's the default com-
       mand it would run?  The same script as you're currently running!  This
       is actually a stealth "fork" hidden inside an "open(2,3,n)" call.  See "Safe
       Pipe Opens" in(1,8) perlipc for details.

       Mixing Reads and Writes

       It is possible to specify both read(2,n,1 builtins) and write(1,2) access.  All you do is
       add a "+" symbol in(1,8) front of the redirection.  But as in(1,8) the shell,
       using a less-than on a file(1,n) never creates a new file(1,n); it only opens an
       existing one.  On the other hand, using a greater-than always clobbers
       (truncates to zero length) an existing file(1,n), or creates a brand-new one
       if(3,n) there isn't an old one.  Adding a "+" for read-write doesn't affect
       whether it only works on existing files or always clobbers existing

           open(2,3,n)(WTMP, "+< /usr/adm/wtmp")
               || die "can't open(2,3,n) /usr/adm/wtmp: $!";

           open(2,3,n)(SCREEN, "+> lkscreen")
               || die "can't open(2,3,n) lkscreen: $!";

           open(2,3,n)(LOGFILE, "+>> /var/log/applog"
               || die "can't open(2,3,n) /var/log/applog: $!";

       The first one won't create a new file(1,n), and the second one will always
       clobber an old one.  The third one will create a new file(1,n) if(3,n) necessary
       and not clobber an old one, and it will allow you to read(2,n,1 builtins) at any point
       in(1,8) the file(1,n), but all writes will always go to the end.  In short, the
       first case is substantially more common than the second and third
       cases, which are almost always wrong.  (If you know C, the plus in(1,8)
       Perl's "open(2,3,n)" is historically derived from the one in(1,8) C's fopen(3S),
       which it ultimately calls.)

       In fact, when it comes to updating a file(1,n), unless you're working on a
       binary file(1,n) as in(1,8) the WTMP case above, you probably don't want to use
       this approach for updating.  Instead, Perl's -i flag comes to the res-
       cue.  The following command takes all the C, C++, or yacc source or
       header files and changes all their foo's to bar's, leaving the old ver-
       sion(1,3,5) in(1,8) the original filename with a ".orig" tacked on the end:

           $ perl -i.orig -pe 's/\bfoo\b/bar/g' *.[Cchy]

       This is a short cut for some renaming games that are really the best
       way to update(7,n) textfiles.  See the second question in(1,8) perlfaq5 for more


       One of the most common uses for "open(2,3,n)" is one you never even notice.
       When you process the ARGV filehandle using "<ARGV>", Perl actually does
       an implicit open(2,3,n) on each file(1,n) in(1,8) @ARGV.  Thus a program called like

           $ myprogram file1 file2 file3

       Can have all its files opened and processed one at a time(1,2,n) using a con-
       struct no more complex than:

           while (<>) {
               # do something with $_

       If @ARGV is empty when the loop first begins, Perl pretends you've
       opened up minus, that is, the standard input.  In fact, $ARGV, the cur-
       rently open(2,3,n) file(1,n) during "<ARGV>" processing, is even set(7,n,1 builtins) to "-" in(1,8)
       these circumstances.

       You are welcome to pre-process your @ARGV before starting the loop to
       make sure it's to your liking.  One reason to do this might be to
       remove command options beginning with a minus.  While you can always
       roll the simple ones by hand, the Getopts modules are good for this:

           use Getopt::Std;

           # -v, -D, -o ARG, sets $opt_v, $opt_D, $opt_o

           # -v, -D, -o ARG, sets $args{v}, $args{D}, $args{o}
           getopts("vDo:", \%args);

       Or the standard Getopt::Long module to permit named(5,8) arguments:

           use Getopt::Long;
           GetOptions( "verbose"  => \$verbose,        # --verbose
                       "Debug"    => \$debug,          # --Debug
                       "output=s" => \$output );
                   # --output=somestring or --output somestring

       Another reason for preprocessing arguments is to make an empty argument
       list default to all files:

           @ARGV = glob(1,3,7,n)("*") unless @ARGV;

       You could even filter(1,3x,3x curs_util) out all but plain, text files.  This is a bit
       silent, of course, and you might prefer to mention them on the way.

           @ARGV = grep { -f && -T } @ARGV;

       If you're using the -n or -p command-line options, you should put
       changes to @ARGV in(1,8) a "BEGIN{}" block.

       Remember that a normal "open(2,3,n)" has special properties, in(1,8) that it might
       call fopen(3S) or it might called popen(3S), depending on what its
       argument looks like; that's why it's sometimes called "magic(4,5) open(2,3,n)".
       Here's an example:

           $pwdinfo = `domainname` =~ /^(\(none\))?$/
                           ? '< /etc/passwd(1,5)'
                           : 'ypcat passwd(1,5) |';

           open(2,3,n)(PWD, $pwdinfo)
                       or die "can't open(2,3,n) $pwdinfo: $!";

       This sort(1,3) of thing also comes into play in(1,8) filter(1,3x,3x curs_util) processing.  Because
       "<ARGV>" processing employs the normal, shell-style Perl "open(2,3,n)", it
       respects all the special things we've already seen:

           $ myprogram f1 "cmd1|" - f2 "cmd2|" f3 < tmpfile

       That program will read(2,n,1 builtins) from the file(1,n) f1, the process cmd1, standard
       input (tmpfile in(1,8) this case), the f2 file(1,n), the cmd2 command, and
       finally the f3 file.

       Yes, this also means that if(3,n) you have files named(5,8) "-" (and so on) in(1,8)
       your directory, they won't be processed as literal files by "open(2,3,n)".
       You'll need to pass them as "./-", much as you would for the rm pro-
       gram, or you could use "sysopen" as described below.

       One of the more interesting applications is to change files of a cer-
       tain name into pipes.  For example, to autoprocess gzipped or com-
       pressed files by decompressing them with gzip:

           @ARGV = map { /^\.(gz|Z)$/ ? "gzip -dc $_ |" : $_  } @ARGV;

       Or, if(3,n) you have the GET program installed from LWP, you can fetch URLs
       before processing them:

           @ARGV = map { m#^\w+://# ? "GET $_ |" : $_ } @ARGV;

       It's not for nothing that this is called magic(4,5) "<ARGV>".  Pretty nifty,

Open A la C
       If you want the convenience of the shell, then Perl's "open(2,3,n)" is defi-
       nitely the way to go.  On the other hand, if(3,n) you want finer precision
       than C's simplistic fopen(3S) provides you should look(1,8,3 Search::Dict) to Perl's
       "sysopen", which is a direct hook into the open(2,3,n)(2) system call.  That
       does mean it's a bit more involved, but that's the price of precision.

       "sysopen" takes 3 (or 4) arguments.

           sysopen HANDLE, PATH, FLAGS, [MASK]

       The HANDLE argument is a filehandle just as with "open(2,3,n)".  The PATH is a
       literal path, one that doesn't pay attention to any greater-thans or
       less-thans or pipes or minuses, nor ignore white space.  If it's there,
       it's part of the path.  The FLAGS argument contains one or more values
       derived from the Fcntl module that have been or'd together using the
       bitwise "|" operator.  The final argument, the MASK, is optional; if(3,n)
       present, it is combined with the user's current umask for the creation
       mode of the file.  You should usually omit this.

       Although the traditional values of read-only, write-only, and read-
       write(1,2) are 0, 1, and 2 respectively, this is known not to hold true on
       some systems.  Instead, it's best to load(7,n) in(1,8) the appropriate constants
       first from the Fcntl module, which supplies the following standard

           O_RDONLY            Read only
           O_WRONLY            Write only
           O_RDWR              Read and write(1,2)
           O_CREAT             Create the file(1,n) if(3,n) it doesn't exist
           O_EXCL              Fail if(3,n) the file(1,n) already exists
           O_APPEND            Append to the file(1,n)
           O_TRUNC             Truncate the file(1,n)
           O_NONBLOCK          Non-blocking access(2,5)

       Less common flags that are sometimes available on some operating sys-
       tems include "O_BINARY", "O_TEXT", "O_SHLOCK", "O_EXLOCK", "O_DEFER",
       "O_SYNC", "O_ASYNC", "O_DSYNC", "O_RSYNC", "O_NOCTTY", "O_NDELAY" and
       "O_LARGEFILE".  Consult your open(2,3,n)(2) manpage or its local equivalent
       for details.  (Note: starting from Perl release 5.6 the "O_LARGEFILE"
       flag, if(3,n) available, is automatically added to the sysopen() flags
       because large files are the default.)

       Here's how to use "sysopen" to emulate the simple "open(2,3,n)" calls we had
       before.  We'll omit the "|| die $!" checks for clarity, but make sure
       you always check the return values in(1,8) real code.  These aren't quite
       the same, since "open(2,3,n)" will trim leading and trailing white space, but
       you'll get the idea.

       To open(2,3,n) a file(1,n) for reading:

           open(2,3,n)(FH, "< $path");
           sysopen(FH, $path, O_RDONLY);

       To open(2,3,n) a file(1,n) for writing, creating a new file(1,n) if(3,n) needed or else trun-
       cating an old file:

           open(2,3,n)(FH, "> $path");
           sysopen(FH, $path, O_WRONLY | O_TRUNC | O_CREAT);

       To open(2,3,n) a file(1,n) for appending, creating one if(3,n) necessary:

           open(2,3,n)(FH, ">> $path");
           sysopen(FH, $path, O_WRONLY | O_APPEND | O_CREAT);

       To open(2,3,n) a file(1,n) for update(7,n), where the file(1,n) must already exist:

           open(2,3,n)(FH, "+< $path");
           sysopen(FH, $path, O_RDWR);

       And here are things you can do with "sysopen" that you cannot do with a
       regular "open(2,3,n)".  As you'll see, it's just a matter of controlling the
       flags in(1,8) the third argument.

       To open(2,3,n) a file(1,n) for writing, creating a new file(1,n) which must not previ-
       ously exist:

           sysopen(FH, $path, O_WRONLY | O_EXCL | O_CREAT);

       To open(2,3,n) a file(1,n) for appending, where that file(1,n) must already exist:

           sysopen(FH, $path, O_WRONLY | O_APPEND);

       To open(2,3,n) a file(1,n) for update(7,n), creating a new file(1,n) if(3,n) necessary:

           sysopen(FH, $path, O_RDWR | O_CREAT);

       To open(2,3,n) a file(1,n) for update(7,n), where that file(1,n) must not already exist:

           sysopen(FH, $path, O_RDWR | O_EXCL | O_CREAT);

       To open(2,3,n) a file(1,n) without blocking, creating one if(3,n) necessary:

           sysopen(FH, $path, O_WRONLY | O_NONBLOCK | O_CREAT);

       Permissions A la mode

       If you omit the MASK argument to "sysopen", Perl uses the octal value
       0666.  The normal MASK to use for executables and directories should be
       0777, and for anything else, 0666.

       Why so permissive?  Well, it isn't really.  The MASK will be modified
       by your process's current "umask".  A umask is a number representing
       disabled permissions bits; that is, bits that will not be turned on in(1,8)
       the created files' permissions field.

       For example, if(3,n) your "umask" were 027, then the 020 part would disable
       the group from writing, and the 007 part would disable others from
       reading, writing, or executing.  Under these conditions, passing
       "sysopen" 0666 would create a file(1,n) with mode 0640, since "0666 & ~027"
       is 0640.

       You should seldom use the MASK argument to "sysopen()".  That takes
       away the user's freedom to choose what permission new files will have.
       Denying choice is almost always a bad thing.  One exception would be
       for cases where sensitive or private data is being stored, such as with
       mail(1,8) folders, cookie files, and internal temporary files.

Obscure Open Tricks
       Re-Opening Files (dups)

       Sometimes you already have a filehandle open(2,3,n), and want to make another
       handle that's a duplicate of the first one.  In the shell, we place an
       ampersand in(1,8) front of a file(1,n) descriptor number when doing redirections.
       For example, "2>&1" makes descriptor 2 (that's STDERR in(1,8) Perl) be redi-
       rected into descriptor 1 (which is usually Perl's STDOUT).  The same is
       essentially true in(1,8) Perl: a filename that begins with an ampersand is
       treated instead as a file(1,n) descriptor if(3,n) a number, or as a filehandle if(3,n)
       a string.

           open(2,3,n)(SAVEOUT, ">&SAVEERR") || die "couldn't dup SAVEERR: $!";
           open(2,3,n)(MHCONTEXT, "<&4")     || die "couldn't dup fd4: $!";

       That means that if(3,n) a function is expecting a filename, but you don't
       want to give it a filename because you already have the file(1,n) open(2,3,n), you
       can just pass the filehandle with a leading ampersand.  It's best to
       use a fully qualified handle though, just in(1,8) case the function happens
       to be in(1,8) a different package:


       This way if(3,n) somefunction() is planning on opening its argument, it can
       just use the already opened handle.  This differs from passing a han-
       dle, because with a handle, you don't open(2,3,n) the file.  Here you have
       something you can pass to open.

       If you have one of those tricky, newfangled I/O objects that the C++
       folks are raving about, then this doesn't work because those aren't a
       proper filehandle in(1,8) the native Perl sense.  You'll have to use
       fileno() to pull out the proper descriptor number, assuming you can:

           use IO::Socket;
           $handle = IO::Socket::INET->new("");
           $fd = $handle->fileno;
           somefunction("&$fd");  # not an indirect function call

       It can be easier (and certainly will be faster) just to use real file-
       handles though:

           use IO::Socket;
           local *REMOTE = IO::Socket::INET->new("");
           die "can't connect" unless defined(fileno(REMOTE));

       If the filehandle or descriptor number is preceded not just with a sim-
       ple "&" but rather with a "&=" combination, then Perl will not create a
       completely new descriptor opened to the same place using the dup(2)
       system call.  Instead, it will just make something of an alias to the
       existing one using the fdopen(3S) library call  This is slightly more
       parsimonious of systems resources, although this is less(1,3) a concern
       these days.  Here's an example of that:

           $fd = $ENV{"MHCONTEXTFD"};
           open(2,3,n)(MHCONTEXT, "<&=$fd")   or die "couldn't fdopen $fd: $!";

       If you're using magic(4,5) "<ARGV>", you could even pass in(1,8) as a command
       line argument in(1,8) @ARGV something like "<&=$MHCONTEXTFD", but we've
       never seen anyone actually do this.

       Dispelling the Dweomer

       Perl is more of a DWIMmer language than something like Java--where DWIM
       is an acronym for "do what I mean".  But this principle sometimes leads
       to more hidden magic(4,5) than one knows what to do with.  In this way, Perl
       is also filled with dweomer, an obscure word meaning an enchantment.
       Sometimes, Perl's DWIMmer is just too much like dweomer for comfort.

       If magic(4,5) "open(2,3,n)" is a bit too magical for you, you don't have to turn to
       "sysopen".  To open(2,3,n) a file(1,n) with arbitrary weird characters in(1,8) it, it's
       necessary to protect any leading and trailing whitespace.  Leading
       whitespace is protected by inserting a "./" in(1,8) front of a filename that
       starts with whitespace.  Trailing whitespace is protected by appending
       an ASCII NUL byte ("\0") at the end of the string.

           $file(1,n) =~ s#^(\s)#./$1#;
           open(2,3,n)(FH, "< $file(1,n)\0")   || die "can't open(2,3,n) $file: $!";

       This assumes, of course, that your system considers dot the current
       working directory, slash the directory separator, and disallows ASCII
       NULs within a valid filename.  Most systems follow these conventions,
       including all POSIX systems as well as proprietary Microsoft systems.
       The only vaguely popular system that doesn't work this way is the pro-
       prietary Macintosh system, which uses a colon where the rest of us use
       a slash.  Maybe "sysopen" isn't such a bad idea after all.

       If you want to use "<ARGV>" processing in(1,8) a totally boring and non-mag-
       ical way, you could do this first:

           #   "Sam sat on the ground and put his head in(1,8) his hands.
           #   'I wish I had never come here, and I don't want to see
           #   no more magic(4,5),' he said, and fell silent."
           for (@ARGV) {
               $_ .= "\0";
           while (<>) {
               # now process $_

       But be warned that users(1,5) will not appreciate being unable to use "-" to
       mean standard input, per the standard convention.

       Paths as Opens

       You've probably noticed how Perl's "warn" and "die" functions can pro-
       duce messages like:

           Some warning at scriptname line 29, <FH> line 7.

       That's because you opened a filehandle FH, and had read(2,n,1 builtins) in(1,8) seven
       records from it.  But what was the name of the file(1,n), rather than the

       If you aren't running with "strict refs", or if(3,n) you've turned them off
       temporarily, then all you have to do is this:

           open(2,3,n)($path, "< $path") || die "can't open(2,3,n) $path: $!";
           while (<$path>) {
               # whatever

       Since you're using the pathname of the file(1,n) as its handle, you'll get
       warnings more like

           Some warning at scriptname line 29, </etc/motd> line 7.

       Single Argument Open

       Remember how we said that Perl's open(2,3,n) took two arguments?  That was a
       passive prevarication.  You see, it can also take just one argument.
       If and only if(3,n) the variable is a global variable, not a lexical, you
       can pass "open(2,3,n)" just one argument, the filehandle, and it will get the
       path from the global scalar variable of the same name.

           $FILE = "/etc/motd";
           open(2,3,n) FILE or die "can't open(2,3,n) $FILE: $!";
           while (<FILE>) {
               # whatever

       Why is this here?  Someone has to cater to the hysterical porpoises.
       It's something that's been in(1,8) Perl since the very beginning, if(3,n) not

       Playing with STDIN and STDOUT

       One clever move(3x,7,3x curs_move) with STDOUT is to explicitly close(2,7,n) it when you're done
       with the program.

           END { close(2,7,n)(STDOUT) || die "can't close(2,7,n) stdout: $!" }

       If you don't do this, and your program fills up the disk partition due
       to a command line redirection, it won't report the error(8,n) exit(3,n,1 builtins) with a
       failure status.

       You don't have to accept(2,8) the STDIN and STDOUT you were given.  You are
       welcome to reopen them if(3,n) you'd like.

           open(2,3,n)(STDIN, "< datafile")
               || die "can't open(2,3,n) datafile: $!";

           open(2,3,n)(STDOUT, "> output")
               || die "can't open(2,3,n) output: $!";

       And then these can be accessed directly or passed on to subprocesses.
       This makes it look(1,8,3 Search::Dict) as though the program were initially invoked with
       those redirections from the command line.

       It's probably more interesting to connect these to pipes.  For example:

           $pager = $ENV{PAGER} || "(less(1,3) || more)";
           open(2,3,n)(STDOUT, "| $pager")
               || die "can't fork a pager: $!";

       This makes it appear as though your program were called with its stdout
       already piped into your pager.  You can also use this kind of thing in(1,8)
       conjunction with an implicit fork to yourself.  You might do this if(3,n)
       you would rather handle the post processing in(1,8) your own program, just
       in(1,8) a different process:

           while (<>) {

           sub head {
               my $lines = shift || 20;
               return if(3,n) $pid = open(2,3,n)(STDOUT, "|-");       # return if(3,n) parent
               die "cannot fork: $!" unless defined $pid;
               while (<STDIN>) {
                   last if(3,n) --$lines < 0;
               exit(3,n,1 builtins);

       This technique can be applied to repeatedly push as many filters on
       your output stream as you wish.

Other I/O Issues
       These topics aren't really arguments related to "open(2,3,n)" or "sysopen",
       but they do affect what you do with your open(2,3,n) files.

       Opening Non-File Files

       When is a file(1,n) not a file(1,n)?  Well, you could say when it exists but
       isn't a plain file.   We'll check whether it's a symbolic link(1,2) first,
       just in(1,8) case.

           if(3,n) (-l $file(1,n) || ! -f _) {
               print "$file(1,n) is not a plain file(1,n)\n";

       What other kinds of files are there than, well, files?  Directories,
       symbolic links, named(5,8) pipes, Unix-domain sockets, and block and charac-
       ter devices.  Those are all files, too--just not plain files.  This
       isn't the same issue as being a text file. Not all text files are plain
       files.  Not all plain files are text files.  That's why there are sepa-
       rate "-f" and "-T" file(1,n) tests.

       To open(2,3,n) a directory, you should use the "opendir" function, then
       process it with "readdir(2,3)", carefully restoring the directory name if(3,n)

           opendir(DIR, $dirname) or die "can't opendir $dirname: $!";
           while (defined($file(1,n) = readdir(2,3)(DIR))) {
               # do something with "$dirname/$file(1,n)"

       If you want to process directories recursively, it's better to use the
       File::Find module.  For example, this prints out all files recursively
       and adds a slash to their names if(3,n) the file(1,n) is a directory.

           @ARGV = qw(.) unless @ARGV;
           use File::Find;
           find sub { print $File::Find::name, -d && '/', "\n" }, @ARGV;

       This finds all bogus symbolic links beneath a particular directory:

           find sub { print "$File::Find::name\n" if(3,n) -l && !-e }, $dir;

       As you see, with symbolic links, you can just pretend that it is what
       it points to.  Or, if(3,n) you want to know what it points to, then "read-
       link(1,2)" is called for:

           if(3,n) (-l $file(1,n)) {
               if(3,n) (defined($whither = readlink(1,2)($file(1,n)))) {
                   print "$file(1,n) points to $whither\n";
               } else {
                   print "$file(1,n) points nowhere: $!\n";

       Opening Named Pipes

       Named pipes are a different matter.  You pretend they're regular files,
       but their opens will normally block until there is both a reader and a
       writer.  You can read(2,n,1 builtins) more about them in(1,8) "Named Pipes" in(1,8) perlipc.
       Unix-domain sockets are rather different beasts as well; they're
       described in(1,8) "Unix-Domain TCP Clients and Servers" in(1,8) perlipc.

       When it comes to opening devices, it can be easy and it can be tricky.
       We'll assume that if(3,n) you're opening up a block device, you know what
       you're doing.  The character devices are more interesting.  These are
       typically used for modems, mice, and some kinds of printers.  This is
       described in(1,8) "How do I read(2,n,1 builtins) and write(1,2) the serial port?" in(1,8) perlfaq8
       It's often enough to open(2,3,n) them carefully:

           sysopen(TTYIN, "/dev/ttyS1", O_RDWR | O_NDELAY | O_NOCTTY)
                       # (O_NOCTTY no longer needed on POSIX systems)
               or die "can't open(2,3,n) /dev/ttyS1: $!";
           open(2,3,n)(TTYOUT, "+>&TTYIN")
               or die "can't dup TTYIN: $!";

           $ofh = select(2,7,2 select_tut)(TTYOUT); $| = 1; select(2,7,2 select_tut)($ofh);

           print TTYOUT "+++at\015";
           $answer = <TTYIN>;

       With descriptors that you haven't opened using "sysopen", such as sock-
       ets, you can set(7,n,1 builtins) them to be non-blocking using "fcntl":

           use Fcntl;
           my $old_flags = fcntl($handle, F_GETFL, 0)
               or die "can't get flags: $!";
           fcntl($handle, F_SETFL, $old_flags | O_NONBLOCK)
               or die "can't set(7,n,1 builtins) non blocking: $!";

       Rather than losing yourself in(1,8) a morass of twisting, turning "ioctl"s,
       all dissimilar, if(3,n) you're going to manipulate ttys, it's best to make
       calls out to the stty(1) program if(3,n) you have it, or else use the porta-
       ble POSIX interface.  To figure this all out, you'll need to read(2,n,1 builtins) the
       termios(3) manpage, which describes the POSIX interface to tty(1,4) devices,
       and then POSIX, which describes Perl's interface to POSIX.  There are
       also some high-level modules on CPAN that can help you with these
       games.  Check out Term::ReadKey and Term::ReadLine.

       Opening Sockets

       What else can you open(2,3,n)?  To open(2,3,n) a connection using sockets, you won't
       use one of Perl's two open(2,3,n) functions.  See "Sockets: Client/Server Com-
       munication" in(1,8) perlipc for that.  Here's an example.  Once you have it,
       you can use FH as a bidirectional filehandle.

           use IO::Socket;
           local *FH = IO::Socket::INET->new("");

       For opening up a URL, the LWP modules from CPAN are just what the doc-
       tor ordered.  There's no filehandle interface, but it's still easy to
       get the contents of a document:

           use LWP::Simple;
           $doc = get('');

       Binary Files

       On certain legacy systems with what could charitably be called termi-
       nally convoluted (some would say broken) I/O models, a file(1,n) isn't a
       file--at least, not with respect to the C standard I/O library.  On
       these old systems whose libraries (but not kernels) distinguish between
       text and binary streams, to get files to behave properly you'll have to
       bend over backwards to avoid nasty problems.  On such infelicitous sys-
       tems, sockets and pipes are already opened in(1,8) binary mode, and there is
       currently no way to turn that off.  With files, you have more options.

       Another option is to use the "binmode" function on the appropriate han-
       dles before doing regular I/O on them:

           while (<STDIN>) { print }

       Passing "sysopen" a non-standard flag option will also open(2,3,n) the file(1,n) in(1,8)
       binary mode on those systems that support it.  This is the equivalent
       of opening the file(1,n) normally, then calling "binmode" on the handle.

           sysopen(BINDAT, "", O_RDWR | O_BINARY)
               || die "can't open(2,3,n) $!";

       Now you can use "read(2,n,1 builtins)" and "print" on that handle without worrying
       about the non-standard system I/O library breaking your data.  It's not
       a pretty picture, but then, legacy systems seldom are.  CP/M will be
       with us until the end of days, and after.

       On systems with exotic I/O systems, it turns out that, astonishingly
       enough, even unbuffered I/O using "sysread" and "syswrite" might do
       sneaky data mutilation behind your back.

           while (sysread(WHENCE, $buf, 1024)) {
               syswrite(WHITHER, $buf, length($buf));

       Depending on the vicissitudes of your runtime system, even these calls
       may need "binmode" or "O_BINARY" first.  Systems known to be free of
       such difficulties include Unix, the Mac OS, Plan 9, and Inferno.

       File Locking

       In a multitasking environment, you may need to be careful not to col-
       lide with other processes who want to do I/O on the same files as you
       are working on.  You'll often need shared or exclusive locks on files
       for reading and writing respectively.  You might just pretend that only
       exclusive locks exist.

       Never use the existence of a file(1,n) "-e $file(1,n)" as a locking indication,
       because there is a race condition between the test for the existence of
       the file(1,n) and its creation.  It's possible for another process to create
       a file(1,n) in(1,8) the slice of time(1,2,n) between your existence check and your
       attempt to create the file.  Atomicity is critical.

       Perl's most portable locking interface is via the "flock(1,2)" function,
       whose simplicity is emulated on systems that don't directly support it
       such as SysV or Windows.  The underlying semantics may affect how it
       all works, so you should learn how "flock(1,2)" is implemented on your sys-
       tem's port of Perl.

       File locking does not lock out another process that would like to do
       I/O.  A file(1,n) lock only locks out others trying to get a lock, not pro-
       cesses trying to do I/O.  Because locks are advisory, if(3,n) one process
       uses locking and another doesn't, all bets are off.

       By default, the "flock(1,2)" call will block until a lock is granted.  A
       request for a shared lock will be granted as soon as there is no exclu-
       sive locker.  A request for an exclusive lock will be granted as soon
       as there is no locker of any kind.  Locks are on file(1,n) descriptors, not
       file(1,n) names.  You can't lock a file(1,n) until you open(2,3,n) it, and you can't
       hold on to a lock once the file(1,n) has been closed.

       Here's how to get a blocking shared lock on a file(1,n), typically used for

           use 5.004;
           use Fcntl qw(:DEFAULT :flock);
           open(2,3,n)(FH, "< filename")  or die "can't open(2,3,n) filename: $!";
           flock(1,2)(FH, LOCK_SH)      or die "can't lock filename: $!";
           # now read(2,n,1 builtins) from FH

       You can get a non-blocking lock by using "LOCK_NB".

           flock(1,2)(FH, LOCK_SH | LOCK_NB)
               or die "can't lock filename: $!";

       This can be useful for producing more user-friendly behaviour by warn-
       ing if(3,n) you're going to be blocking:

           use 5.004;
           use Fcntl qw(:DEFAULT :flock);
           open(2,3,n)(FH, "< filename")  or die "can't open(2,3,n) filename: $!";
           unless (flock(1,2)(FH, LOCK_SH | LOCK_NB)) {
               $| = 1;
               print "Waiting for lock...";
               flock(1,2)(FH, LOCK_SH)  or die "can't lock filename: $!";
               print "got it.\n"
           # now read(2,n,1 builtins) from FH

       To get an exclusive lock, typically used for writing, you have to be
       careful.  We "sysopen" the file(1,n) so it can be locked before it gets(3,n) emp-
       tied.  You can get a nonblocking version(1,3,5) using "LOCK_EX | LOCK_NB".

           use 5.004;
           use Fcntl qw(:DEFAULT :flock);
           sysopen(FH, "filename", O_WRONLY | O_CREAT)
               or die "can't open(2,3,n) filename: $!";
           flock(1,2)(FH, LOCK_EX)
               or die "can't lock filename: $!";
           truncate(2,7)(FH, 0)
               or die "can't truncate(2,7) filename: $!";
           # now write(1,2) to FH

       Finally, due to the uncounted millions who cannot be dissuaded from
       wasting cycles on useless vanity devices called hit counters, here's
       how to increment a number in(1,8) a file(1,n) safely:

           use Fcntl qw(:DEFAULT :flock);

           sysopen(FH, "numfile", O_RDWR | O_CREAT)
               or die "can't open(2,3,n) numfile: $!";
           # autoflush FH
           $ofh = select(2,7,2 select_tut)(FH); $| = 1; select(2,7,2 select_tut) ($ofh);
           flock(1,2)(FH, LOCK_EX)
               or die "can't write-lock numfile: $!";

           $num = <FH> || 0;
           seek(FH, 0, 0)
               or die "can't rewind numfile : $!";
           print FH $num+1, "\n"
               or die "can't write(1,2) numfile: $!";

           truncate(2,7)(FH, tell(FH))
               or die "can't truncate(2,7) numfile: $!";
               or die "can't close(2,7,n) numfile: $!";

       IO Layers

       In Perl 5.8.0 a new I/O framework called "PerlIO" was introduced.  This
       is a new "plumbing" for all the I/O happening in(1,8) Perl; for the most
       part everything will work just as it did, but PerlIO also brought in(1,8)
       some new features such as the ability to think of I/O as "layers".  One
       I/O layer may in(1,8) addition to just moving the data also do transforma-
       tions on the data.  Such transformations may include compression and
       decompression, encryption and decryption, and transforming between var-
       ious character encodings.

       Full discussion about the features of PerlIO is out of scope for this
       tutorial, but here is how to recognize the layers being used:

          The three-(or more)-argument form of "open(2,3,n)" is being used and the
           second argument contains something else in(1,8) addition to the usual
           '<', '>', '>>', '|' and their variants, for example:

               open(2,3,n)(my $fh, "<:utf8", $fn);

          The two-argument form of "binmode" is being used, for example

               binmode($fh, ":encoding(utf16)");

       For more detailed discussion about PerlIO see PerlIO; for more detailed
       discussion about Unicode and I/O see perluniintro.

       The "open(2,3,n)" and "sysopen" functions in(1,8) perlfunc(1); the system open(2,3,n)(2),
       dup(2), fopen(3), and fdopen(3) manpages; the POSIX documentation.

       Copyright 1998 Tom Christiansen.

       This documentation is free; you can redistribute it and/or modify it
       under the same terms as Perl itself.

       Irrespective of its distribution, all code examples in(1,8) these files are
       hereby placed into the public domain.  You are permitted and encouraged
       to use this code in(1,8) your own programs for fun or for profit as you see
       fit.  A simple comment in(1,8) the code giving credit would be courteous but
       is not required.

       First release: Sat Jan  9 08:09:11 MST 1999

perl v5.8.5                       2004-04-23                    PERLOPENTUT(1)

References for this manual (incoming links)