Cari di Perl 
    Perl User Manual
Daftar Isi
(Sebelumnya) Create a directoryOpen a directory (Berikutnya)
Functions for filehandles, files, or directories

Open a file, pipe, or descriptor

Daftar Isi

  • open FILEHANDLE,EXPR

  • open FILEHANDLE,MODE,EXPR
  • open FILEHANDLE,MODE,EXPR,LIST
  • open FILEHANDLE,MODE,REFERENCE
  • open FILEHANDLE

    Opens the file whose filename is given by EXPR, and associates it withFILEHANDLE.

    Simple examples to open a file for reading:

    1. open(my $fh, "<", "input.txt")
    2. or die "cannot open < input.txt: $!";

    and for writing:

    1. open(my $fh, ">", "output.txt")
    2. or die "cannot open > output.txt: $!";

    (The following is a comprehensive reference to open(): for a gentlerintroduction you may consider perlopentut.)

    If FILEHANDLE is an undefined scalar variable (or array or hash element), anew filehandle is autovivified, meaning that the variable is assigned areference to a newly allocated anonymous filehandle. Otherwise ifFILEHANDLE is an expression, its value is the real filehandle. (This isconsidered a symbolic reference, so use strict "refs" should not bein effect.)

    If EXPR is omitted, the global (package) scalar variable of the samename as the FILEHANDLE contains the filename. (Note that lexical variables--those declared with my or state--will not work for thispurpose; so if you're using my or state, specify EXPR in yourcall to open.)

    If three (or more) arguments are specified, the open mode (includingoptional encoding) in the second argument are distinct from the filename inthe third. If MODE is < or nothing, the file is opened for input.If MODE is >, the file is opened for output, with existing filesfirst being truncated ("clobbered") and nonexisting files newly created.If MODE is >>, the file is opened for appending, again beingcreated if necessary.

    You can put a + in front of the > or < toindicate that you want both read and write access to the file; thus+< is almost always preferred for read/write updates--the +> mode would clobber the file first. You can't usually useeither read-write mode for updating textfiles, since they havevariable-length records. See the -i switch in perlrun for abetter approach. The file is created with permissions of 0666modified by the process's umask value.

    These various prefixes correspond to the fopen(3) modes of r,r+, w, w+, a, and a+.

    In the one- and two-argument forms of the call, the mode and filenameshould be concatenated (in that order), preferably separated by whitespace. You can--but shouldn't--omit the mode in these forms when that modeis <. It is always safe to use the two-argument form of open ifthe filename argument is a known literal.

    For three or more arguments if MODE is |-, the filename isinterpreted as a command to which output is to be piped, and if MODEis -|, the filename is interpreted as a command that pipesoutput to us. In the two-argument (and one-argument) form, one shouldreplace dash (-) with the command.See Using open() for IPC in perlipc for more examples of this.(You are not allowed to open to a command that pipes both in andout, but see IPC::Open2, IPC::Open3, andBidirectional Communication with Another Process in perlipc foralternatives.)

    In the form of pipe opens taking three or more arguments, if LIST is specified(extra arguments after the command name) then LIST becomes argumentsto the command invoked if the platform supports it. The meaning ofopen with more than three arguments for non-pipe modes is not yetdefined, but experimental "layers" may give extra LIST argumentsmeaning.

    In the two-argument (and one-argument) form, opening <- or - opens STDIN and opening >- opens STDOUT.

    You may (and usually should) use the three-argument form of open to specifyI/O layers (sometimes referred to as "disciplines") to apply to the handlethat affect how the input and output are processed (see open andPerlIO for more details). For example:

    1. open(my $fh, "<:encoding(UTF-8)", "filename")
    2. || die "can't open UTF-8 encoded filename: $!";

    opens the UTF8-encoded file containing Unicode characters;see perluniintro. Note that if layers are specified in thethree-argument form, then default layers stored in ${^OPEN} (see perlvar;usually set by the open pragma or the switch -CioD) are ignored.Those layers will also be ignored if you specifying a colon with no namefollowing it. In that case the default layer for the operating system(:raw on Unix, :crlf on Windows) is used.

    Open returns nonzero on success, the undefined value otherwise. Ifthe open involved a pipe, the return value happens to be the pid ofthe subprocess.

    If you're running Perl on a system that distinguishes between textfiles and binary files, then you should check out binmode for tipsfor dealing with this. The key distinction between systems that needbinmode and those that don't is their text file formats. Systemslike Unix, Mac OS, and Plan 9, that end lines with a singlecharacter and encode that character in C as "\n" do notneed binmode. The rest need it.

    When opening a file, it's seldom a good idea to continue if the request failed, so open is frequently used withdie. Even if die won't do what you want (say, in a CGI script,where you want to format a suitable error message (but there aremodules that can help with that problem)) always checkthe return value from opening a file.

    As a special case the three-argument form with a read/write mode and the thirdargument being undef:

    1. open(my $tmp, "+>", undef) or die ...

    opens a filehandle to an anonymous temporary file. Also using +<works for symmetry, but you really should consider writing somethingto the temporary file first. You will need to seek() to do thereading.

    Since v5.8.0, Perl has built using PerlIO by default. Unless you'vechanged this (such as building Perl with Configure -Uuseperlio), you canopen filehandles directly to Perl scalars via:

    1. open($fh, ">", \$variable) || ..

    To (re)open STDOUT or STDERR as an in-memory file, close it first:

    1. close STDOUT;
    2. open(STDOUT, ">", \$variable)
    3. or die "Can't open STDOUT: $!";

    General examples:

    1. $ARTICLE = 100;
    2. open(ARTICLE) or die "Can't find article $ARTICLE: $!\n";
    3. while (<ARTICLE>) {...
    4. open(LOG, ">>/usr/spool/news/twitlog"); # (log is reserved)
    5. # if the open fails, output is discarded
    6. open(my $dbase, "+<", "dbase.mine") # open for update
    7. or die "Can't open 'dbase.mine' for update: $!";
    8. open(my $dbase, "+<dbase.mine") # ditto
    9. or die "Can't open 'dbase.mine' for update: $!";
    10. open(ARTICLE, "-|", "caesar <$article") # decrypt article
    11. or die "Can't start caesar: $!";
    12. open(ARTICLE, "caesar <$article |") # ditto
    13. or die "Can't start caesar: $!";
    14. open(EXTRACT, "|sort >Tmp$$") # $$ is our process id
    15. or die "Can't start sort: $!";
    16. # in-memory files
    17. open(MEMORY, ">", \$var)
    18. or die "Can't open memory file: $!";
    19. print MEMORY "foo!\n"; # output will appear in $var
    20. # process argument list of files along with any includes
    21. foreach $file (@ARGV) {
    22. process($file, "fh00");
    23. }
    24. sub process {
    25. my($filename, $input) = @_;
    26. $input++; # this is a string increment
    27. unless (open($input, "<", $filename)) {
    28. print STDERR "Can't open $filename: $!\n";
    29. return;
    30. }
    31. local $_;
    32. while (<$input>) { # note use of indirection
    33. if (/^#include "(.*)"/) {
    34. process($1, $input);
    35. next;
    36. }
    37. #... # whatever
    38. }
    39. }

    See perliol for detailed info on PerlIO.

    You may also, in the Bourne shell tradition, specify an EXPR beginningwith >&, in which case the rest of the string is interpretedas the name of a filehandle (or file descriptor, if numeric) to beduped (as dup(2)) and opened. You may use & after >,>>, <, +>, +>>, and +<.The mode you specify should match the mode of the original filehandle.(Duping a filehandle does not take into account any existing contentsof IO buffers.) If you use the three-argumentform, then you can pass either anumber, the name of a filehandle, or the normal "reference to a glob".

    Here is a script that saves, redirects, and restores STDOUT andSTDERR using various methods:

    1. #!/usr/bin/perl
    2. open(my $oldout, ">&STDOUT") or die "Can't dup STDOUT: $!";
    3. open(OLDERR, ">&", \*STDERR) or die "Can't dup STDERR: $!";
    4. open(STDOUT, '>', "foo.out") or die "Can't redirect STDOUT: $!";
    5. open(STDERR, ">&STDOUT") or die "Can't dup STDOUT: $!";
    6. select STDERR; $| = 1; # make unbuffered
    7. select STDOUT; $| = 1; # make unbuffered
    8. print STDOUT "stdout 1\n"; # this works for
    9. print STDERR "stderr 1\n"; # subprocesses too
    10. open(STDOUT, ">&", $oldout) or die "Can't dup \$oldout: $!";
    11. open(STDERR, ">&OLDERR") or die "Can't dup OLDERR: $!";
    12. print STDOUT "stdout 2\n";
    13. print STDERR "stderr 2\n";

    If you specify '<&=X', where X is a file descriptor numberor a filehandle, then Perl will do an equivalent of C's fdopen ofthat file descriptor (and not call dup(2)); this is moreparsimonious of file descriptors. For example:

    1. # open for input, reusing the fileno of $fd
    2. open(FILEHANDLE, "<&=$fd")

    or

    1. open(FILEHANDLE, "<&=", $fd)

    or

    1. # open for append, using the fileno of OLDFH
    2. open(FH, ">>&=", OLDFH)

    or

    1. open(FH, ">>&=OLDFH")

    Being parsimonious on filehandles is also useful (besides beingparsimonious) for example when something is dependent on filedescriptors, like for example locking using flock(). If you do justopen(A, ">>&B"), the filehandle A will not have the same filedescriptor as B, and therefore flock(A) will not flock(B) nor viceversa. But with open(A, ">>&=B"), the filehandles will sharethe same underlying system file descriptor.

    Note that under Perls older than 5.8.0, Perl uses the standard C library's'fdopen() to implement the = functionality. On many Unix systems,fdopen() fails when file descriptors exceed a certain value, typically 255.For Perls 5.8.0 and later, PerlIO is (most often) the default.

    You can see whether your Perl was built with PerlIO by running perl -Vand looking for the useperlio= line. If useperlio is define, youhave PerlIO; otherwise you don't.

    If you open a pipe on the command - (that is, specify either |- or -|with the one- or two-argument forms of open), an implicit fork is done, so open returns twice: in the parentprocess it returns the pidof the child process, and in the child process it returns (a defined) 0.Use defined($pid) or // to determine whether the open was successful.

    For example, use either

    1. $child_pid = open(FROM_KID, "-|") // die "can't fork: $!";

    or $child_pid = open(TO_KID, "|-") // die "can't fork: $!";

    followed by

    1. if ($child_pid) {
    2. # am the parent:
    3. # either write TO_KID or else read FROM_KID
    4. ...
    5. wait $child_pid;
    6. } else {
    7. # am the child; use STDIN/STDOUT normally
    8. ...
    9. exit;
    10. }

    The filehandle behaves normally for the parent, but I/O to thatfilehandle is piped from/to the STDOUT/STDIN of the child process.In the child process, the filehandle isn't opened--I/O happens from/tothe new STDOUT/STDIN. Typically this is used like the normalpiped open when you want to exercise more control over just how thepipe command gets executed, such as when running setuid andyou don't want to have to scan shell commands for metacharacters.

    The following blocks are more or less equivalent:

    1. open(FOO, "|tr '[a-z]' '[A-Z]'");
    2. open(FOO, "|-", "tr '[a-z]' '[A-Z]'");
    3. open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
    4. open(FOO, "|-", "tr", '[a-z]', '[A-Z]');
    5. open(FOO, "cat -n '$file'|");
    6. open(FOO, "-|", "cat -n '$file'");
    7. open(FOO, "-|") || exec "cat", "-n", $file;
    8. open(FOO, "-|", "cat", "-n", $file);

    The last two examples in each block show the pipe as "list form", which isnot yet supported on all platforms. A good rule of thumb is that ifyour platform has a real fork() (in other words, if your platform isUnix, including Linux and MacOS X), you can use the list form. You would want to use the list form of the pipe so you can pass literal argumentsto the command without risk of the shell interpreting any shell metacharactersin them. However, this also bars you from opening pipes to commandsthat intentionally contain shell metacharacters, such as:

    1. open(FOO, "|cat -n | expand -4 | lpr")
    2. // die "Can't open pipeline to lpr: $!";

    See Safe Pipe Opens in perlipc for more examples of this.

    Beginning with v5.6.0, Perl will attempt to flush all files opened foroutput before any operation that may do a fork, but this may not besupported on some platforms (see perlport). To be safe, you may needto set $| ($AUTOFLUSH in English) or call the autoflush() methodof IO::Handle on any open handles.

    On systems that support a close-on-exec flag on files, the flag willbe set for the newly opened file descriptor as determined by the valueof $^F. See $^F in perlvar.

    Closing any piped filehandle causes the parent process to wait for thechild to finish, then returns the status value in $? and${^CHILD_ERROR_NATIVE}.

    The filename passed to the one- and two-argument forms of open() willhave leading and trailing whitespace deleted and normalredirection characters honored. This property, known as "magic open",can often be used to good effect. A user could specify a filename of"rsh cat file |", or you could change certain filenames as needed:

    1. $filename =~ s/(.*\.gz)\s*$/gzip -dc < $1|/;
    2. open(FH, $filename) or die "Can't open $filename: $!";

    Use the three-argument form to open a file with arbitrary weird characters in it,

    1. open(FOO, "<", $file)
    2. || die "can't open < $file: $!";

    otherwise it's necessary to protect any leading and trailing whitespace:

    1. $file =~ s#^(\s)#./$1#;
    2. open(FOO, "< $file\0")
    3. || die "open failed: $!";

    (this may not work on some bizarre filesystems). One shouldconscientiously choose between the magic and three-argument formof open():

    1. open(IN, $ARGV[0]) || die "can't open $ARGV[0]: $!";

    will allow the user to specify an argument of the form "rsh cat file |",but will not work on a filename that happens to have a trailing space, while

    1. open(IN, "<", $ARGV[0])
    2. || die "can't open < $ARGV[0]: $!";

    will have exactly the opposite restrictions.

    If you want a "real" C open (see open(2) on your system), then youshould use the sysopen function, which involves no such magic (but mayuse subtly different filemodes than Perl open(), which is mapped to Cfopen()). This is another way to protect your filenames frominterpretation. For example:

    1. use IO::Handle;
    2. sysopen(HANDLE, $path, O_RDWR|O_CREAT|O_EXCL)
    3. or die "sysopen $path: $!";
    4. $oldfh = select(HANDLE); $| = 1; select($oldfh);
    5. print HANDLE "stuff $$\n";
    6. seek(HANDLE, 0, 0);
    7. print "File contains: ", <HANDLE>;

    Using the constructor from the IO::Handle package (or one of itssubclasses, such as IO::File or IO::Socket), you can generate anonymousfilehandles that have the scope of the variables used to hold them, thenautomatically (but silently) close once their reference counts becomezero, typically at scope exit:

    1. use IO::File;
    2. #...
    3. sub read_myfile_munged {
    4. my $ALL = shift;
    5. # or just leave it undef to autoviv
    6. my $handle = IO::File->new;
    7. open($handle, "<", "myfile") or die "myfile: $!";
    8. $first = <$handle>
    9. or return (); # Automatically closed here.
    10. mung($first) or die "mung failed"; # Or here.
    11. return (first, <$handle>) if $ALL; # Or here.
    12. return $first; # Or here.
    13. }

    WARNING: The previous example has a bug because the automaticclose that happens when the refcount on handle does notproperly detect and report failures. Always close the handleyourself and inspect the return value.

    1. close($handle)
    2. || warn "close failed: $!";

    See seek for some details about mixing reading and writing.

    Portability issues: open in perlport.

 
Source : perldoc.perl.org - Official documentation for the Perl programming language
Site maintained by Jon Allen (JJ)     See the project page for more details
Documentation maintained by the Perl 5 Porters
(Sebelumnya) Create a directoryOpen a directory (Berikutnya)