home *** CD-ROM | disk | FTP | other *** search
/ Il CD di internet / CD.iso / SOURCE / D / PERL / PERL-4.036 / PERL-4 / perl-4.036 / Info / perl.info-3 < prev    next >
Encoding:
GNU Info File  |  1994-07-08  |  38.2 KB  |  981 lines

  1. This is Info file perl.info, produced by Makeinfo-1.55 from the input
  2. file perltexi.
  3.  
  4.    This file documents perl, Practical Extraction and Report Language,
  5. and was originally based on Larry Wall's unix-style man page for perl.
  6.  
  7.    GNU Texinfo version adapted by Jeff Kellem
  8. <composer@Beyond.Dreams.ORG>.
  9.  
  10.    Copyright (C) 1989, 1990, 1991, 1992, 1993 Larry Wall Texinfo
  11. version Copyright (C) 1990, 1991, 1993 Jeff Kellem
  12.  
  13.    Permission is granted to make and distribute verbatim copies of this
  14. manual provided the copyright notice and this permission notice are
  15. preserved on all copies.
  16.  
  17.    Permission is granted to copy and distribute modified versions of
  18. this manual under the conditions for verbatim copying, provided also
  19. that the sections entitled "GNU General Public License" and "Conditions
  20. for Using Perl" are included exactly as in the original, and provided
  21. that the entire resulting derived work is distributed under the terms
  22. of a permission notice identical to this one.
  23.  
  24.    Permission is granted to copy and distribute translations of this
  25. manual into another language, under the above conditions for modified
  26. versions, except that the section entitled "GNU General Public License"
  27. and this permission notice may be included in translations approved by
  28. the Free Software Foundation instead of in the original English.
  29.  
  30. 
  31. File: perl.info,  Node: String Functions,  Next: Array and List Functions,  Prev: Structure Conversion,  Up: Commands
  32.  
  33. String Functions
  34. ================
  35.  
  36. chop(LIST)
  37. chop(VARIABLE)
  38. chop VARIABLE
  39. chop
  40.      Chops off the last character of a string and returns the character
  41.      chopped.  It's used primarily to remove the newline from the end
  42.      of an input record, but is much more efficient than `s/\n//'
  43.      because it neither scans nor copies the string.  If VARIABLE is
  44.      omitted, chops `$_'.  Example:
  45.  
  46.           while (<>) {
  47.                   chop;   # avoid \n on last field
  48.                   @array = split(/:/);
  49.                   ...
  50.           }
  51.  
  52.      You can actually chop anything that's an lvalue, including an
  53.      assignment:
  54.  
  55.           chop($cwd = `pwd`);
  56.           chop($answer = <STDIN>);
  57.  
  58.      If you chop a list, each element is chopped.  Only the value of
  59.      the last chop is returned.
  60.  
  61. crypt(PLAINTEXT,SALT)
  62.      Encrypts a string exactly like the `crypt()' function in the C
  63.      library.  Useful for checking the password file for lousy
  64.      passwords.  Only the guys wearing white hats should do this.
  65.  
  66. index(STR,SUBSTR,POSITION)
  67. index(STR,SUBSTR)
  68.      Returns the position of the first occurrence of SUBSTR in STR at
  69.      or after POSITION.  If POSITION is omitted, starts searching from
  70.      the beginning of the string.  The return value is based at 0, or
  71.      whatever you've set the `$[' variable to.  If the substring is not
  72.      found, returns one less than the base, ordinarily -1.
  73.  
  74. length(EXPR)
  75. length EXPR
  76. length
  77.      Returns the length in characters of the value of EXPR.  If EXPR is
  78.      omitted, returns length of `$_'.
  79.  
  80. rindex(STR,SUBSTR,POSITION)
  81. rindex(STR,SUBSTR)
  82.      Works just like `index' except that it returns the position of the
  83.      LAST occurrence of SUBSTR in STR.  If POSITION is specified,
  84.      returns the last occurrence at or before that position.
  85.  
  86. substr(EXPR,OFFSET,LEN)
  87. substr(EXPR,OFFSET)
  88.      Extracts a substring out of EXPR and returns it.  First character
  89.      is at offset 0, or whatever you've set `$[' to.  If OFFSET is
  90.      negative, starts that far from the end of the string.  If LEN is
  91.      omitted, returns everything to the end of the string.  You can use
  92.      the `substr()' function as an lvalue, in which case EXPR must be
  93.      an lvalue.  If you assign something shorter than LEN, the string
  94.      will shrink, and if you assign something longer than LEN, the
  95.      string will grow to accommodate it.  To keep the string the same
  96.      length you may need to pad or chop your value using `sprintf()'.
  97.  
  98. 
  99. File: perl.info,  Node: Array and List Functions,  Next: File Operations,  Prev: String Functions,  Up: Commands
  100.  
  101. Array and List Functions
  102. ========================
  103.  
  104. delete $ASSOC{KEY}
  105.      Deletes the specified value from the specified associative array.
  106.      Returns the deleted value, or the undefined value if nothing was
  107.      deleted.  Deleting from $ENV{} modifies the environment.  Deleting
  108.      from an array bound to a dbm file deletes the entry from the dbm
  109.      file.
  110.  
  111.      The following deletes all the values of an associative array:
  112.  
  113.           foreach $key (keys %ARRAY) {
  114.                   delete $ARRAY{$key};
  115.           }
  116.  
  117.      (But it would be faster to use the `reset' command.  Saying `undef
  118.      %ARRAY' is faster yet.)
  119.  
  120. each(ASSOC_ARRAY)
  121. each ASSOC_ARRAY
  122.      Returns a 2 element array consisting of the key and value for the
  123.      next value of an associative array, so that you can iterate over
  124.      it.  Entries are returned in an apparently random order.  When the
  125.      array is entirely read, a null array is returned (which when
  126.      assigned produces a FALSE (0) value).  The next call to `each()'
  127.      after that will start iterating again.  The iterator can be reset
  128.      only by reading all the elements from the array.  You must not
  129.      modify the array while iterating over it.  There is a single
  130.      iterator for each associative array, shared by all `each()',
  131.      `keys()' and `values()' function calls in the program.  The
  132.      following prints out your environment like the `printenv' program,
  133.      only in a different order:
  134.  
  135.           while (($key,$value) = each %ENV) {
  136.                   print "$key=$value\n";
  137.           }
  138.  
  139.      See also `keys()' and `values()'.
  140.  
  141. grep(EXPR,LIST)
  142.      Evaluates EXPR for each element of LIST (locally setting `$_' to
  143.      each element) and returns the array value consisting of those
  144.      elements for which the expression evaluated to true.  In a scalar
  145.      context, returns the number of times the expression was true.
  146.  
  147.           @foo = grep(!/^#/, @bar);    # weed out comments
  148.  
  149.      Note that, since `$_' is a reference into the array value, it can
  150.      be used to modify the elements of the array.  While this is useful
  151.      and supported, it can cause bizarre results if the LIST is not a
  152.      named array.
  153.  
  154. join(EXPR,LIST)
  155. join(EXPR,ARRAY)
  156.      Joins the separate strings of LIST or ARRAY into a single string
  157.      with fields separated by the value of EXPR, and returns the
  158.      string.  Example:
  159.  
  160.           $_ = join(':', $login,$passwd,$uid,$gid,$gcos,$home,$shell);
  161.  
  162.      See `split' function.
  163.  
  164. keys(ASSOC_ARRAY)
  165. keys ASSOC_ARRAY
  166.      Returns a normal array consisting of all the keys of the named
  167.      associative array.  The keys are returned in an apparently random
  168.      order, but it is the same order as either the `values()' or
  169.      `each()' function produces (given that the associative array has
  170.      not been modified).  Here is yet another way to print your
  171.      environment:
  172.  
  173.           @keys = keys %ENV;
  174.           @values = values %ENV;
  175.           while ($#keys >= 0) {
  176.                   print pop(@keys), '=', pop(@values), "\n";
  177.           }
  178.  
  179.      or how about sorted by key:
  180.  
  181.           foreach $key (sort(keys %ENV)) {
  182.                   print $key, '=', $ENV{$key}, "\n";
  183.           }
  184.  
  185. pop(ARRAY)
  186. pop ARRAY
  187.      Pops and returns the last value of the array, shortening the array
  188.      by 1.  Has the same effect as:
  189.  
  190.           $tmp = $ARRAY[$#ARRAY--];
  191.  
  192.      If there are no elements in the array, returns the undefined value.
  193.  
  194. push(ARRAY,LIST)
  195.      Treats ARRAY (`@' is optional) as a stack, and pushes the values
  196.      of LIST onto the end of ARRAY.  The length of ARRAY increases by
  197.      the length of LIST.  Has the same effect as:
  198.  
  199.           for $value (LIST) {
  200.                   $ARRAY[++$#ARRAY] = $value;
  201.           }
  202.  
  203.      but is more efficient.
  204.  
  205. reverse(LIST)
  206. reverse LIST
  207.      In an array context, returns an array value consisting of the
  208.      elements of LIST in the opposite order.  In a scalar context,
  209.      returns a string value consisting of the bytes of the first
  210.      element of LIST in the opposite order.
  211.  
  212. shift(ARRAY)
  213. shift ARRAY
  214. shift
  215.      Shifts the first value of the array off and returns it, shortening
  216.      the array by 1 and moving everything down.  If there are no
  217.      elements in the array, returns the undefined value.  If ARRAY is
  218.      omitted, shifts the `@ARGV' array in the main program, and the
  219.      `@_' array in subroutines.  (This is determined lexically.)  See
  220.      also `unshift()', `push()' and `pop()'.  `shift()' and `unshift()'
  221.      do the same thing to the left end of an array that `push()' and
  222.      `pop()' do to the right end.
  223.  
  224. sort(SUBROUTINE LIST)
  225. sort(LIST)
  226. sort SUBROUTINE LIST
  227. sort BLOCK LIST
  228. sort LIST
  229.      Sorts the LIST and returns the sorted array value.  Nonexistent
  230.      values of arrays are stripped out.  If SUBROUTINE or BLOCK is
  231.      omitted, sorts in standard string comparison order.  If SUBROUTINE
  232.      is specified, gives the name of a subroutine that returns an
  233.      integer less than, equal to, or greater than 0, depending on how
  234.      the elements of the array are to be ordered.  (The `<=>' and `cmp'
  235.      operators are extremely useful in such routines.) SUBROUTINE may
  236.      be a scalar variable name, in which case the value provides the
  237.      name of the subroutine to use.  In place of a SUBROUTINE name, you
  238.      can provide a BLOCK as an anonymous, in-line sort subroutine.
  239.  
  240.      In the interests of efficiency the normal calling code for
  241.      subroutines is bypassed, with the following effects: the
  242.      subroutine may not be a recursive subroutine, and the two elements
  243.      to be compared are passed into the subroutine not via `@_' but as
  244.      `$a' and `$b' (see example below).  They are passed by reference
  245.      so don't modify `$a' and `$b'.  Examples:
  246.  
  247.           # sort lexically
  248.           @articles = sort @files;
  249.           
  250.           # same thing, but with explicit sort routine
  251.           @articles = sort { $a cmp $b } @files;
  252.           
  253.           # same thing in reversed order
  254.           @articles = sort { $b cmp $a } @files;
  255.           
  256.           # sort numerically ascending
  257.           @articles = sort { $a <=> $b } @files;
  258.           
  259.           # sort numerically descending
  260.           @articles = sort { $b <=> $a } @files;
  261.           
  262.           # sort using explicit subroutine name
  263.           sub byage {
  264.               $age{$a} <=> $age{$b};    # presuming integers
  265.           }
  266.           @sortedclass = sort byage @class;
  267.           
  268.           sub reverse { $b cmp $a; }
  269.           @harry = ('dog','cat','x','Cain','Abel');
  270.           @george = ('gone','chased','yz','Punished','Axed');
  271.           print sort @harry;
  272.                   # prints AbelCaincatdogx
  273.           print sort reverse @harry;
  274.                   # prints xdogcatCainAbel
  275.           print sort @george, 'to', @harry;
  276.                   # prints AbelAxedCainPunishedcatchaseddoggonetoxyz
  277.  
  278. splice(ARRAY,OFFSET,LENGTH,LIST)
  279. splice(ARRAY,OFFSET,LENGTH)
  280. splice(ARRAY,OFFSET)
  281.      Removes the elements designated by OFFSET and LENGTH from an
  282.      array, and replaces them with the elements of LIST, if any.
  283.      Returns the elements removed from the array.  The array grows or
  284.      shrinks as necessary.  If LENGTH is omitted, removes everything
  285.      from OFFSET onward.  The following equivalencies hold (assuming
  286.      `$[ == 0'):
  287.  
  288.           push(@a,$x,$y)         splice(@a,$#x+1,0,$x,$y)
  289.           pop(@a)                splice(@a,-1)
  290.           shift(@a)              splice(@a,0,1)
  291.           unshift(@a,$x,$y)      splice(@a,0,0,$x,$y)
  292.           $a[$x] = $y            splice(@a,$x,1,$y);
  293.  
  294.      Example, assuming array lengths are passed before arrays:
  295.  
  296.           sub aeq {      # compare two array values
  297.                   local(@a) = splice(@_,0,shift);
  298.                   local(@b) = splice(@_,0,shift);
  299.                   return 0 unless @a == @b;     # same len?
  300.                   while (@a) {
  301.                       return 0 if pop(@a) ne pop(@b);
  302.                   }
  303.                   return 1;
  304.           }
  305.           if (&aeq($len,@foo[1..$len],0+@bar,@bar)) { ... }
  306.  
  307. split(/PATTERN/,EXPR,LIMIT)
  308. split(/PATTERN/,EXPR)
  309. split(/PATTERN/)
  310. split
  311.      Splits a string into an array of strings, and returns it.  (If not
  312.      in an array context, returns the number of fields found and splits
  313.      into the `@_' array.  (In an array context, you can force the
  314.      split into `@_' by using `??' as the pattern delimiters, but it
  315.      still returns the array value.))  If EXPR is omitted, splits the
  316.      `$_' string.  If PATTERN is also omitted, splits on whitespace
  317.      (`/[\t\n]+/').  Anything matching PATTERN is taken to be a
  318.      delimiter separating the fields.  (Note that the delimiter may be
  319.      longer than one character.)  If LIMIT is specified, splits into no
  320.      more than that many fields (though it may split into fewer).  If
  321.      LIMIT is unspecified, trailing null fields are stripped (which
  322.      potential users of `pop()' would do well to remember).  A pattern
  323.      matching the null string (not to be confused with a null pattern
  324.      `//', which is just one member of the set of patterns matching a
  325.      null string) will split the value of EXPR into separate characters
  326.      at each point it matches that way.  For example:
  327.  
  328.           print join(':', split(/ */, 'hi there'));
  329.  
  330.      produces the output `h:i:t:h:e:r:e'.
  331.  
  332.      The LIMIT parameter can be used to partially split a line
  333.  
  334.           ($login, $passwd, $remainder) = split(/:/, $_, 3);
  335.  
  336.      (When assigning to a list, if LIMIT is omitted, perl supplies a
  337.      LIMIT one larger than the number of variables in the list, to
  338.      avoid unnecessary work.  For the list above LIMIT would have been
  339.      4 by default.  In time critical applications it behooves you not to
  340.      split into more fields than you really need.)
  341.  
  342.      If the PATTERN contains parentheses, additional array elements are
  343.      created from each matching substring in the delimiter.
  344.  
  345.           split(/([,-])/,"1-10,20");
  346.  
  347.      produces the array value
  348.  
  349.           (1,'-',10,',',20)
  350.  
  351.      The pattern /PATTERN/ may be replaced with an expression to
  352.      specify patterns that vary at runtime.  (To do runtime compilation
  353.      only once, use `/$variable/o'.)  As a special case, specifying a
  354.      space (' ') will split on white space just as split with no
  355.      arguments does, but leading white space does *NOT* produce a null
  356.      first field.  Thus, split(' ') can be used to emulate `awk''s
  357.      default behavior, whereas `split(/ /)' will give you as many null
  358.      initial fields as there are leading spaces.
  359.  
  360.      Example:
  361.  
  362.           open(passwd, '/etc/passwd');
  363.           while (<passwd>) {
  364.                   ($login, $passwd, $uid, $gid, $gcos, $home, $shell)
  365.                           = split(/:/);
  366.                   ...
  367.           }
  368.  
  369.      (Note that `$shell' above will still have a newline on it.  See
  370.      `chop()'.)  See also `join'.
  371.  
  372. unshift(ARRAY,LIST)
  373.      Does the opposite of a `shift'.  Or the opposite of a `push',
  374.      depending on how you look at it.  Prepends list to the front of the
  375.      array, and returns the number of elements in the new array.
  376.  
  377.           unshift(ARGV, '-e') unless $ARGV[0] =~ /^-/;
  378.  
  379. values(ASSOC_ARRAY)
  380. values ASSOC_ARRAY
  381.      Returns a normal array consisting of all the values of the named
  382.      associative array.  The values are returned in an apparently random
  383.      order, but it is the same order as either the `keys()' or `each()'
  384.      function would produce on the same array.  See also `keys()' and
  385.      `each()'.
  386.  
  387. 
  388. File: perl.info,  Node: File Operations,  Next: Directory Reading Functions,  Prev: Array and List Functions,  Up: Commands
  389.  
  390. File Operations
  391. ===============
  392.  
  393. chmod(LIST)
  394. chmod LIST
  395.      Changes the permissions of a list of files.  The first element of
  396.      the list must be the numerical mode.  Returns the number of files
  397.      successfully changed.
  398.  
  399.           $cnt = chmod 0755, 'foo', 'bar';
  400.           chmod 0755, @executables;
  401.  
  402. chown(LIST)
  403. chown LIST
  404.      Changes the owner (and group) of a list of files.  The first two
  405.      elements of the list must be the *NUMERICAL* uid and gid, in that
  406.      order.  Returns the number of files successfully changed.
  407.  
  408.           $cnt = chown $uid, $gid, 'foo', 'bar';
  409.           chown $uid, $gid, @filenames;
  410.  
  411.      Here's an example that looks up non-numeric uids in the passwd
  412.      file:
  413.  
  414.           print "User: ";
  415.           $user = <STDIN>;
  416.           chop($user);
  417.           print "Files: "
  418.           $pattern = <STDIN>;
  419.           chop($pattern);
  420.           open(pass, '/etc/passwd') || die "Can't open passwd: $!\n";
  421.           while (<pass>) {
  422.                   ($login,$pass,$uid,$gid) = split(/:/);
  423.                   $uid{$login} = $uid;
  424.                   $gid{$login} = $gid;
  425.           }
  426.           @ary = <${pattern}>; # get filenames
  427.           if ($uid{$user} eq '') {
  428.                   die "$user not in passwd file";
  429.           }
  430.           else {
  431.                   chown $uid{$user}, $gid{$user}, @ary;
  432.           }
  433.  
  434. fcntl(FILEHANDLE,FUNCTION,SCALAR)
  435.      Implements the `fcntl(2)' function.  You'll probably have to say:
  436.  
  437.           require "fcntl.ph";   # probably /usr/local/lib/perl/fcntl.ph
  438.  
  439.      first to get the correct function definitions.  If `fcntl.ph'
  440.      doesn't exist or doesn't have the correct definitions you'll have
  441.      to roll your own, based on your C header files such as
  442.      `<sys/fcntl.h>'.  (There is a perl script called `h2ph' that comes
  443.      with the perl kit which may help you in this.)  Argument
  444.      processing and value return works just like `ioctl' below.  Note
  445.      that `fcntl' will produce a fatal error if used on a machine that
  446.      doesn't implement `fcntl(2)'.
  447.  
  448. fileno(FILEHANDLE)
  449. fileno FILEHANDLE
  450.      Returns the file descriptor for a filehandle.  Useful for
  451.      constructing bitmaps for `select()'.  If FILEHANDLE is an
  452.      expression, the value is taken as the name of the filehandle.
  453.  
  454. flock(FILEHANDLE,OPERATION)
  455.      Calls `flock(2)' on FILEHANDLE.  See manual page for `flock(2)'
  456.      for definition of OPERATION.  Returns true for success, false on
  457.      failure.  Will produce a fatal error if used on a machine that
  458.      doesn't implement `flock(2)'.  Here's a mailbox appender for BSD
  459.      systems.
  460.  
  461.           $LOCK_SH = 1;
  462.           $LOCK_EX = 2;
  463.           $LOCK_NB = 4;
  464.           $LOCK_UN = 8;
  465.           
  466.           sub lock {
  467.               flock(MBOX,$LOCK_EX);
  468.               # and, in case someone appended
  469.               # while we were waiting...
  470.               seek(MBOX, 0, 2);
  471.           }
  472.           
  473.           sub unlock {
  474.               flock(MBOX,$LOCK_UN);
  475.           }
  476.           
  477.           open(MBOX, ">>/usr/spool/mail/$ENV{'USER'}")
  478.                   || die "Can't open mailbox: $!";
  479.           
  480.           do lock();
  481.           print MBOX $msg,"\n\n";
  482.           do unlock();
  483.  
  484. link(OLDFILE,NEWFILE)
  485.      Creates a new filename linked to the old filename.  Returns 1 for
  486.      success, 0 otherwise.
  487.  
  488. lstat(FILEHANDLE)
  489. lstat FILEHANDLE
  490. lstat(EXPR)
  491. lstat SCALARVARIABLE
  492.      Does the same thing as the `stat()' function, but stats a symbolic
  493.      link instead of the file the symbolic link points to.  If symbolic
  494.      links are unimplemented on your system, a normal stat is done.
  495.  
  496. readlink(EXPR)
  497. readlink EXPR
  498. readlink
  499.      Returns the value of a symbolic link, if symbolic links are
  500.      implemented.  If not, gives a fatal error.  If there is some
  501.      system error, returns the undefined value and sets `$!' (errno).
  502.      If EXPR is omitted, uses `$_'.
  503.  
  504. rename(OLDNAME,NEWNAME)
  505.      Changes the name of a file.  Returns 1 for success, 0 otherwise.
  506.      Will not work across filesystem boundaries.
  507.  
  508. stat(FILEHANDLE)
  509. stat FILEHANDLE
  510. stat(EXPR)
  511. stat SCALARVARIABLE
  512.      Returns a 13-element array giving the statistics for a file,
  513.      either the file opened via FILEHANDLE, or named by EXPR.  Returns
  514.      a null list if the `stat' fails.  Typically used as follows:
  515.  
  516.           ($dev,$ino,$mode,$nlink,$uid,$gid,$rdev,$size,
  517.              $atime,$mtime,$ctime,$blksize,$blocks)
  518.                  = stat($filename);
  519.  
  520.      If `stat' is passed the special filehandle consisting of an
  521.      underline (`_'), no stat is done, but the current contents of the
  522.      stat structure from the last stat or filetest are returned.
  523.      Example:
  524.  
  525.           if (-x $file && (($d) = stat(_)) && $d < 0) {
  526.                   print "$file is executable NFS file\n";
  527.           }
  528.  
  529.      (This only works on machines for which the device number is
  530.      negative under NFS.)
  531.  
  532. symlink(OLDFILE,NEWFILE)
  533.      Creates a new filename symbolically linked to the old filename.
  534.      Returns 1 for success, 0 otherwise.  On systems that don't support
  535.      symbolic links, produces a fatal error at run time.  To check for
  536.      that, use eval:
  537.  
  538.           $symlink_exists = (eval 'symlink("","");', $@ eq '');
  539.  
  540. truncate(FILEHANDLE,LENGTH)
  541. truncate(EXPR,LENGTH)
  542.      Truncates the file opened on FILEHANDLE, or named by EXPR, to the
  543.      specified length.  Produces a fatal error if `truncate' isn't
  544.      implemented on your system.
  545.  
  546. unlink(LIST)
  547. unlink LIST
  548. unlink
  549.      Deletes a list of files.  If EXPR is not specified, deletes file
  550.      specified by `$_'.  Returns the number of files successfully
  551.      deleted.
  552.  
  553.           $cnt = unlink 'a', 'b', 'c';
  554.           unlink @goners;
  555.           unlink <*.bak>;
  556.  
  557.      Note: unlink will not delete directories unless you are superuser
  558.      and the `-U' flag is supplied to *perl*.  Even if these conditions
  559.      are met, be warned that unlinking a directory can inflict damage
  560.      on your filesystem.  Use `rmdir' instead.
  561.  
  562. utime(LIST)
  563. utime LIST
  564.      Changes the access and modification times on each file of a list of
  565.      files.  The first two elements of the list must be the NUMERICAL
  566.      access and modification times, in that order.  Returns the number
  567.      of files successfully changed.  The inode modification time of
  568.      each file is set to the current time.  Example of a "touch"
  569.      command:
  570.  
  571.           #!/usr/bin/perl
  572.           $now = time;
  573.           utime $now, $now, @ARGV;
  574.  
  575. 
  576. File: perl.info,  Node: Directory Reading Functions,  Next: Input/Output,  Prev: File Operations,  Up: Commands
  577.  
  578. Directory Reading Functions
  579. ===========================
  580.  
  581. chdir(EXPR)
  582. chdir EXPR
  583. chdir
  584.      Changes the working directory to EXPR, if possible.  If EXPR is
  585.      omitted, changes to home directory.  Returns 1 upon success, 0
  586.      otherwise.  See example under `die'.
  587.  
  588. closedir(DIRHANDLE)
  589. closedir DIRHANDLE
  590.      Closes a directory opened by `opendir()'.
  591.  
  592. mkdir(FILENAME,MODE)
  593.      Creates the directory specified by FILENAME, with permissions
  594.      specified by MODE (as modified by `umask').  If it succeeds it
  595.      returns 1, otherwise it returns 0 and sets `$!' (errno).
  596.  
  597. opendir(DIRHANDLE,EXPR)
  598.      Opens a directory named EXPR for processing by `readdir()',
  599.      `telldir()', `seekdir()', `rewinddir()' and `closedir()'.  Returns
  600.      true if successful.  DIRHANDLEs have their own namespace separate
  601.      from FILEHANDLEs.
  602.  
  603. readdir(DIRHANDLE)
  604. readdir DIRHANDLE
  605.      Returns the next directory entry for a directory opened by
  606.      `opendir()'.  If used in an array context, returns all the rest of
  607.      the entries in the directory.  If there are no more entries,
  608.      returns an undefined value in a scalar context or a null list in
  609.      an array context.
  610.  
  611. rewinddir(DIRHANDLE)
  612. rewinddir DIRHANDLE
  613.      Sets the current position to the beginning of the directory for the
  614.      `readdir()' routine on DIRHANDLE.
  615.  
  616. rmdir(FILENAME)
  617. rmdir FILENAME
  618. rmdir
  619.      Deletes the directory specified by FILENAME if it is empty.  If it
  620.      succeeds it returns 1, otherwise it returns 0 and sets `$!'
  621.      (errno).  If FILENAME is omitted, uses `$_'.
  622.  
  623. seekdir(DIRHANDLE,POS)
  624.      Sets the current position for the `readdir()' routine on
  625.      DIRHANDLE.  POS must be a value returned by `telldir()'.  Has the
  626.      same caveats about possible directory compaction as the
  627.      corresponding system library routine.
  628.  
  629. telldir(DIRHANDLE)
  630. telldir DIRHANDLE
  631.      Returns the current position of the `readdir()' routines on
  632.      DIRHANDLE.  Value may be given to `seekdir()' to access a
  633.      particular location in a directory.  Has the same caveats about
  634.      possible directory compaction as the corresponding system library
  635.      routine.
  636.  
  637. 
  638. File: perl.info,  Node: Input/Output,  Next: Search and Replace Functions,  Prev: Directory Reading Functions,  Up: Commands
  639.  
  640. Input/Output
  641. ============
  642.  
  643. binmode(FILEHANDLE)
  644. binmode FILEHANDLE
  645.      Arranges for the file to be read in *binary* mode in operating
  646.      systems that distinguish between binary and text files.  Files
  647.      that are not read in binary mode have CR LF sequences translated
  648.      to LF on input and LF translated to CR LF on output.  `binmode'
  649.      has no effect under Unix.  If FILEHANDLE is an expression, the
  650.      value is taken as the name of the filehandle.
  651.  
  652. close(FILEHANDLE)
  653. close FILEHANDLE
  654.      Closes the file or pipe associated with the file handle.  You
  655.      don't have to close FILEHANDLE if you are immediately going to do
  656.      another open on it, since open will close it for you.  (See
  657.      `open'.) However, an explicit close on an input file resets the
  658.      line counter (`$.'), while the implicit close done by `open' does
  659.      not.  Also, closing a pipe will wait for the process executing on
  660.      the pipe to complete, in case you want to look at the output of
  661.      the pipe afterwards.  Closing a pipe explicitly also puts the
  662.      status value of the command into `$?'.  Example:
  663.  
  664.           open(OUTPUT, '|sort >foo');     # pipe to sort
  665.           ...         # print stuff to output
  666.           close OUTPUT;           # wait for sort to finish
  667.           open(INPUT, 'foo');     # get sort's results
  668.  
  669.      FILEHANDLE may be an expression whose value gives the real
  670.      filehandle name.
  671.  
  672. eof(FILEHANDLE)
  673. eof()
  674. eof
  675.      Returns 1 if the next read on FILEHANDLE will return end of file,
  676.      or if FILEHANDLE is not open.  FILEHANDLE may be an expression
  677.      whose value gives the real filehandle name.  (Note that this
  678.      function actually reads a character and the `ungetc''s it, so it is
  679.      not very useful in an interactive context.)  An `eof' without an
  680.      argument returns the eof status for the last file read.  Empty
  681.      parentheses `()' may be used to indicate the pseudo file formed of
  682.      the files listed on the command line, i.e. `eof()' is reasonable to
  683.      use inside a `while (<>)' loop to detect the end of only the last
  684.      file.  Use `eof(ARGV)' or `eof' without the parentheses to test
  685.      EACH file in a `while (<>)' loop.  Examples:
  686.  
  687.           # insert dashes just before last line of last file
  688.           while (<>) {
  689.                   if (eof()) {
  690.                           print "--------------\n";
  691.                   }
  692.                   print;
  693.           }
  694.           
  695.           # reset line numbering on each input file
  696.           while (<>) {
  697.                   print "$.\t$_";
  698.                   if (eof) {     # Not eof().
  699.                           close(ARGV);
  700.                   }
  701.           }
  702.  
  703. getc(FILEHANDLE)
  704. getc FILEHANDLE
  705. getc
  706.      Returns the next character from the input file attached to
  707.      FILEHANDLE, or a null string at EOF.  If FILEHANDLE is omitted,
  708.      reads from STDIN.
  709.  
  710. open(FILEHANDLE,EXPR)
  711. open(FILEHANDLE)
  712. open FILEHANDLE
  713.      Opens the file whose filename is given by EXPR, and associates it
  714.      with FILEHANDLE.  If FILEHANDLE is an expression, its value is
  715.      used as the name of the real filehandle wanted.  If EXPR is
  716.      omitted, the scalar variable of the same name as the FILEHANDLE
  717.      contains the filename.  If the filename begins with `<' or
  718.      nothing, the file is opened for input.  If the filename begins
  719.      with `>', the file is opened for output.  If the filename begins
  720.      with `>>', the file is opened for appending.  (You can put a `+'
  721.      in front of the `>' or `<' to indicate that you want both read and
  722.      write access to the file.)  If the filename begins with `|', the
  723.      filename is interpreted as a command to which output is to be
  724.      piped, and if the filename ends with a `|', the filename is
  725.      interpreted as command which pipes input to us.  (You may not have
  726.      a command that pipes both in and out.)  Opening `-' opens `STDIN'
  727.      and opening `>-' opens `STDOUT'.  `open' returns non-zero upon
  728.      success, the undefined value otherwise.  If the open involved a
  729.      pipe, the return value happens to be the pid of the subprocess.
  730.      Examples:
  731.  
  732.           $article = 100;
  733.           open article || die "Can't find article $article: $!\n";
  734.           while (<article>) {...
  735.           
  736.           open(LOG, '>>/usr/spool/news/twitlog');
  737.                                           # (log is reserved)
  738.           
  739.           open(article, "caesar <$article |");
  740.                                           # decrypt article
  741.           
  742.           open(extract, "|sort >/tmp/Tmp$$");
  743.                                           # $$ is our process#
  744.           
  745.           # process argument list of files along with any includes
  746.           
  747.           foreach $file (@ARGV) {
  748.                   do process($file, 'fh00');      # no pun intended
  749.           }
  750.           
  751.           sub process {
  752.                   local($filename, $input) = @_;
  753.                   $input++;               # this is a string increment
  754.                   unless (open($input, $filename)) {
  755.                           print STDERR "Can't open $filename: $!\n";
  756.                           return;
  757.                   }
  758.                   while (<$input>) {     # note the use of indirection
  759.                           if (/^#include "(.*)"/) {
  760.                                   do process($1, $input);
  761.                                   next;
  762.                           }
  763.                           ...         # whatever
  764.                   }
  765.           }
  766.  
  767.      You may also, in the Bourne shell tradition, specify an EXPR
  768.      beginning with `>&', in which case the rest of the string is
  769.      interpreted as the name of a filehandle (or file descriptor, if
  770.      numeric) which is to be duped and opened.  You may use `&' after
  771.      `>', `>>', `<', `+>', `+>>' and `+<'.  The mode you specify should
  772.      match the mode of the original filehandle.  Here is a script that
  773.      saves, redirects, and restores `STDOUT' and `STDERR':
  774.  
  775.           #!/usr/bin/perl
  776.           open(SAVEOUT, ">&STDOUT");
  777.           open(SAVEERR, ">&STDERR");
  778.           
  779.           open(STDOUT, ">foo.out") || die "Can't redirect stdout";
  780.           open(STDERR, ">&STDOUT") || die "Can't dup stdout";
  781.           
  782.           select(STDERR); $| = 1;         # make unbuffered
  783.           select(STDOUT); $| = 1;         # make unbuffered
  784.           
  785.           print STDOUT "stdout 1\n";      # this works for
  786.           print STDERR "stderr 1\n";      # subprocesses too
  787.           
  788.           close(STDOUT);
  789.           close(STDERR);
  790.           
  791.           open(STDOUT, ">&SAVEOUT");
  792.           open(STDERR, ">&SAVEERR");
  793.           
  794.           print STDOUT "stdout 2\n";
  795.           print STDERR "stderr 2\n";
  796.  
  797.      If you open a pipe on the command `-', i.e. either `|-' or `-|',
  798.      then there is an implicit fork done, and the return value of open
  799.      is the pid of the child within the parent process, and 0 within the
  800.      child process.  (Use `defined($pid)' to determine if the `open'
  801.      was successful.)  The filehandle behaves normally for the parent,
  802.      but i/o to that filehandle is piped from/to the `STDOUT'/`STDIN'
  803.      of the child process.  In the child process the filehandle isn't
  804.      opened--i/o happens from/to the new `STDOUT' or `STDIN'.
  805.      Typically this is used like the normal piped `open' when you want
  806.      to exercise more control over just how the pipe command gets
  807.      executed, such as when you are running setuid, and don't want to
  808.      have to scan shell commands for metacharacters.  The following
  809.      pairs are equivalent:
  810.  
  811.           open(FOO, "|tr '[a-z]' '[A-Z]'");
  812.           open(FOO, "|-") || exec 'tr', '[a-z]', '[A-Z]';
  813.           
  814.           open(FOO, "cat -n '$file'|");
  815.           open(FOO, "-|") || exec 'cat', '-n', $file;
  816.  
  817.      Explicitly closing any piped filehandle causes the parent process
  818.      to wait for the child to finish, and returns the status value in
  819.      `$?'.  Note: on any operation which may do a fork, unflushed
  820.      buffers remain unflushed in both processes, which means you may
  821.      need to set `$|' to avoid duplicate output.
  822.  
  823.      The filename that is passed to open will have leading and trailing
  824.      whitespace deleted.  In order to open a file with arbitrary weird
  825.      characters in it, it's necessary to protect any leading and
  826.      trailing whitespace thusly:
  827.  
  828.           $file =~ s#^(\s)#./$1#;
  829.           open(FOO, "< $file\0");
  830.  
  831. pipe(READHANDLE,WRITEHANDLE)
  832.      Opens a pair of connected pipes like the corresponding system call.
  833.      Note that if you set up a loop of piped processes, deadlock can
  834.      occur unless you are very careful.  In addition, note that perl's
  835.      pipes use stdio buffering, so you may need to set `$|' to flush
  836.      your WRITEHANDLE after each command, depending on the application.
  837.      [Requires version 3.0 patchlevel 9.]
  838.  
  839. print(FILEHANDLE LIST)
  840. print(LIST)
  841. print FILEHANDLE LIST
  842. print LIST
  843. print
  844.      Prints a string or a comma-separated list of strings.  Returns
  845.      non-zero if successful.  FILEHANDLE may be a scalar variable name,
  846.      in which case the variable contains the name of the filehandle,
  847.      thus introducing one level of indirection.  (NOTE: If FILEHANDLE
  848.      is a variable and the next token is a term, it may be
  849.      misinterpreted as an operator unless you interpose a `+' or put
  850.      parens around the arguments.)  If FILEHANDLE is omitted, prints by
  851.      default to standard output (or to the last selected output
  852.      channel--see `select()').  If LIST is also omitted, prints `$_' to
  853.      `STDOUT'.  To set the default output channel to something other
  854.      than `STDOUT' use the select operation.  Note that, because
  855.      `print' takes a LIST, anything in the LIST is evaluated in an
  856.      array context, and any subroutine that you call will have one or
  857.      more of its expressions evaluated in an array context.  Also be
  858.      careful not to follow the `print' keyword with a left parenthesis
  859.      unless you want the corresponding right parenthesis to terminate
  860.      the arguments to the `print'--interpose a `+' or put parens around
  861.      all the arguments.
  862.  
  863. printf(FILEHANDLE LIST)
  864. printf(LIST)
  865. printf FILEHANDLE LIST
  866. printf LIST
  867. printf
  868.      Equivalent to a `print FILEHANDLE sprintf(LIST)'.
  869.  
  870. read(FILEHANDLE,SCALAR,LENGTH,OFFSET)
  871. read(FILEHANDLE,SCALAR,LENGTH)
  872.      Attempts to read LENGTH bytes of data into variable SCALAR from
  873.      the specified FILEHANDLE.  Returns the number of bytes actually
  874.      read, or `undef' if there was an error.  SCALAR will be grown or
  875.      shrunk to the length actually read.  An OFFSET may be specified to
  876.      place the read data at some other place than the beginning of the
  877.      string.  This call is actually implemented in terms of stdio's
  878.      `fread' call.  To get a true `read' system call, see `sysread'.
  879.  
  880. select(RBITS,WBITS,EBITS,TIMEOUT)
  881.      This calls the select system call with the bitmasks specified,
  882.      which can be constructed using `fileno()' and `vec()', along these
  883.      lines:
  884.  
  885.           $rin = $win = $ein = '';
  886.           vec($rin,fileno(STDIN),1) = 1;
  887.           vec($win,fileno(STDOUT),1) = 1;
  888.           $ein = $rin | $win;
  889.  
  890.      If you want to select on many filehandles you might wish to write a
  891.      subroutine:
  892.  
  893.           sub fhbits {
  894.               local(@fhlist) = split(' ',$_[0]);
  895.               local($bits);
  896.               for (@fhlist) {
  897.                   vec($bits,fileno($_),1) = 1;
  898.               }
  899.               $bits;
  900.           }
  901.           $rin = &fhbits('STDIN TTY SOCK');
  902.  
  903.      The usual idiom is:
  904.  
  905.           ($nfound,$timeleft) =
  906.              select($rout=$rin, $wout=$win, $eout=$ein, $timeout);
  907.  
  908.      or to block until something becomes ready:
  909.  
  910.           $nfound = select($rout=$rin, $wout=$win,
  911.                                   $eout=$ein, undef);
  912.  
  913.      Any of the bitmasks can also be `undef'.  The timeout, if
  914.      specified, is in seconds, which may be fractional.  NOTE: not all
  915.      implementations are capable of returning the `$timeleft'.  If not,
  916.      they always return `$timeleft' equal to the supplied `$timeout'.
  917.  
  918. seek(FILEHANDLE,POSITION,WHENCE)
  919.      Randomly positions the file pointer for FILEHANDLE, just like the
  920.      `fseek()' call of stdio.  FILEHANDLE may be an expression whose
  921.      value gives the name of the filehandle.  Returns 1 upon success, 0
  922.      otherwise.
  923.  
  924. select(FILEHANDLE)
  925. select
  926.      Returns the currently selected filehandle.  Sets the current
  927.      default filehandle for output, if FILEHANDLE is supplied.  This
  928.      has two effects: first, a `write' or a `print' without a filehandle
  929.      will default to this FILEHANDLE.  Second, references to variables
  930.      related to output will refer to this output channel.  For example,
  931.      if you have to set the top of form format for more than one output
  932.      channel, you might do the following:
  933.  
  934.           select(REPORT1);
  935.           $^ = 'report1_top';
  936.           select(REPORT2);
  937.           $^ = 'report2_top';
  938.  
  939.      FILEHANDLE may be an expression whose value gives the name of the
  940.      actual filehandle.  Thus:
  941.  
  942.           $oldfh = select(STDERR); $| = 1; select($oldfh);
  943.  
  944. tell(FILEHANDLE)
  945. tell FILEHANDLE
  946. tell
  947.      Returns the current file position for FILEHANDLE.  FILEHANDLE may
  948.      be an expression whose value gives the name of the actual
  949.      filehandle.  If FILEHANDLE is omitted, assumes the file last read.
  950.  
  951. write(FILEHANDLE)
  952. write(EXPR)
  953. write
  954.      Writes a formatted record (possibly multi-line) to the specified
  955.      file, using the format associated with that file.  By default the
  956.      format for a file is the one having the same name is the
  957.      filehandle, but the format for the current output channel (see
  958.      `select') may be set explicitly by assigning the name of the
  959.      format to the `$~' variable.
  960.  
  961.      Top of form processing is handled automatically: if there is
  962.      insufficient room on the current page for the formatted record,
  963.      the page is advanced by writing a form feed, a special top-of-page
  964.      format is used to format the new page header, and then the record
  965.      is written.  By default the top-of-page format is the name of the
  966.      filehandle with `_TOP' appended, but it may be dynamically set to
  967.      the format of your choice by assigning the name to the `$^'
  968.      variable while the filehandle is `select'ed.  The number of lines
  969.      remaining on the current page is in variable `$-', which can be
  970.      set to 0 to force a new page.
  971.  
  972.      If FILEHANDLE is unspecified, output goes to the current default
  973.      output channel, which starts out as `STDOUT' but may be changed by
  974.      the `select' operator.  If the FILEHANDLE is an EXPR, then the
  975.      expression is evaluated and the resulting string is used to look
  976.      up the name of the FILEHANDLE at run time.  *Note Formats::, for
  977.      more info.
  978.  
  979.      Note that `write' is NOT the opposite of `read'.
  980.  
  981.