Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
tree: 904d84e064
Fetching contributors…

Cannot retrieve contributors at this time

1245 lines (811 sloc) 82.355 kb
[%# DO NOT EDIT THIS FILE, AUTO GENERATED FROM THE perlfaq -%]
[%-
# Used to get info from htmlify to ttree
page.import({
title => "perlfaq5",
section => "faq",
description
=> "Perl Frequently Asked Questions, Perl FAQ",
keywords => "perl, perl faq, perlfaq"
});
perlfaq_version = 5.0150037;
-%]
<div class="pod">
<ul id="index">
<li><a href="#NAME">NAME</a></li>
<li><a href="#DESCRIPTION">DESCRIPTION</a>
<ul>
<li><a href="#How-do-I-flush-unbuffer-an-output-filehandle-Why-must-I-do-this-">How do I flush/unbuffer an output filehandle? Why must I do this? </a></li>
<li><a href="#How-do-I-change-delete-or-insert-a-line-in-a-file-or-append-to-the-beginning-of-a-file-">How do I change, delete, or insert a line in a file, or append to the beginning of a file? </a></li>
<li><a href="#How-do-I-count-the-number-of-lines-in-a-file-">How do I count the number of lines in a file? </a></li>
<li><a href="#How-do-I-delete-the-last-N-lines-from-a-file-">How do I delete the last N lines from a file? </a></li>
<li><a href="#How-can-I-use-Perls--i-option-from-within-a-program-">How can I use Perl&#39;s <code>-i</code> option from within a program? </a></li>
<li><a href="#How-can-I-copy-a-file-">How can I copy a file? </a></li>
<li><a href="#How-do-I-make-a-temporary-file-name-">How do I make a temporary file name? </a></li>
<li><a href="#How-can-I-manipulate-fixed-record-length-files-">How can I manipulate fixed-record-length files? </a></li>
<li><a href="#How-can-I-make-a-filehandle-local-to-a-subroutine-How-do-I-pass-filehandles-between-subroutines-How-do-I-make-an-array-of-filehandles-">How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? </a></li>
<li><a href="#How-can-I-use-a-filehandle-indirectly-">How can I use a filehandle indirectly? </a></li>
<li><a href="#How-can-I-set-up-a-footer-format-to-be-used-with-write-">How can I set up a footer format to be used with write()? </a></li>
<li><a href="#How-can-I-write-into-a-string-">How can I write() into a string? </a></li>
<li><a href="#How-can-I-open-a-filehandle-to-a-string-">How can I open a filehandle to a string? </a></li>
<li><a href="#How-can-I-output-my-numbers-with-commas-added-">How can I output my numbers with commas added? </a></li>
<li><a href="#How-can-I-translate-tildes-in-a-filename-">How can I translate tildes (~) in a filename? </a></li>
<li><a href="#How-come-when-I-open-a-file-read-write-it-wipes-it-out-">How come when I open a file read-write it wipes it out? </a></li>
<li><a href="#Why-do-I-sometimes-get-an-Argument-list-too-long-when-I-use-">Why do I sometimes get an &quot;Argument list too long&quot; when I use &lt;*&gt;? </a></li>
<li><a href="#Is-there-a-leak-bug-in-glob-">Is there a leak/bug in glob()? </a></li>
<li><a href="#How-can-I-open-a-file-with-a-leading-or-trailing-blanks-">How can I open a file with a leading &quot;&gt;&quot; or trailing blanks? </a></li>
<li><a href="#How-can-I-reliably-rename-a-file-">How can I reliably rename a file? </a></li>
<li><a href="#How-can-I-lock-a-file-">How can I lock a file? </a></li>
<li><a href="#Why-cant-I-just-open-FH-file.lock-">Why can&#39;t I just open(FH, &quot;&gt;file.lock&quot;)? </a></li>
<li><a href="#I-still-dont-get-locking.-I-just-want-to-increment-the-number-in-the-file.-How-can-I-do-this-">I still don&#39;t get locking. I just want to increment the number in the file. How can I do this? </a></li>
<li><a href="#All-I-want-to-do-is-append-a-small-amount-of-text-to-the-end-of-a-file.-Do-I-still-have-to-use-locking-">All I want to do is append a small amount of text to the end of a file. Do I still have to use locking? </a></li>
<li><a href="#How-do-I-randomly-update-a-binary-file-">How do I randomly update a binary file? </a></li>
<li><a href="#How-do-I-get-a-files-timestamp-in-perl-">How do I get a file&#39;s timestamp in perl? </a></li>
<li><a href="#How-do-I-set-a-files-timestamp-in-perl-">How do I set a file&#39;s timestamp in perl? </a></li>
<li><a href="#How-do-I-print-to-more-than-one-file-at-once-">How do I print to more than one file at once? </a></li>
<li><a href="#How-can-I-read-in-an-entire-file-all-at-once-">How can I read in an entire file all at once? </a></li>
<li><a href="#How-can-I-read-in-a-file-by-paragraphs-">How can I read in a file by paragraphs? </a></li>
<li><a href="#How-can-I-read-a-single-character-from-a-file-From-the-keyboard-">How can I read a single character from a file? From the keyboard? </a></li>
<li><a href="#How-can-I-tell-whether-theres-a-character-waiting-on-a-filehandle-">How can I tell whether there&#39;s a character waiting on a filehandle?</a></li>
<li><a href="#How-do-I-do-a-tail--f-in-perl-">How do I do a <code>tail -f</code> in perl? </a></li>
<li><a href="#How-do-I-dup-a-filehandle-in-Perl-">How do I dup() a filehandle in Perl? </a></li>
<li><a href="#How-do-I-close-a-file-descriptor-by-number-">How do I close a file descriptor by number? </a></li>
<li><a href="#Why-cant-I-use-C:-temp-foo-in-DOS-paths-Why-doesnt-C:-temp-foo.exe-work-">Why can&#39;t I use &quot;C:\temp\foo&quot; in DOS paths? Why doesn&#39;t `C:\temp\foo.exe` work? </a></li>
<li><a href="#Why-doesnt-glob-.-get-all-the-files-">Why doesn&#39;t glob(&quot;*.*&quot;) get all the files? </a></li>
<li><a href="#Why-does-Perl-let-me-delete-read-only-files-Why-does--i-clobber-protected-files-Isnt-this-a-bug-in-Perl-">Why does Perl let me delete read-only files? Why does <code>-i</code> clobber protected files? Isn&#39;t this a bug in Perl?</a></li>
<li><a href="#How-do-I-select-a-random-line-from-a-file-">How do I select a random line from a file? </a></li>
<li><a href="#Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines-">Why do I get weird spaces when I print an array of lines?</a></li>
<li><a href="#How-do-I-traverse-a-directory-tree-">How do I traverse a directory tree?</a></li>
<li><a href="#How-do-I-delete-a-directory-tree-">How do I delete a directory tree?</a></li>
<li><a href="#How-do-I-copy-an-entire-directory-">How do I copy an entire directory?</a></li>
</ul>
</li>
<li><a href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a></li>
</ul>
<h1 id="NAME">NAME</h1>
<p>perlfaq5 - Files and Formats</p>
<h1 id="DESCRIPTION">DESCRIPTION</h1>
<p>This section deals with I/O and the &quot;f&quot; issues: filehandles, flushing, formats, and footers.</p>
<h2 id="How-do-I-flush-unbuffer-an-output-filehandle-Why-must-I-do-this-">How do I flush/unbuffer an output filehandle? Why must I do this? </h2>
<p>(contributed by brian d foy)</p>
<p>You might like to read Mark Jason Dominus&#39;s &quot;Suffering From Buffering&quot; at <a href="http://perl.plover.com/FAQs/Buffering.html">http://perl.plover.com/FAQs/Buffering.html</a> .</p>
<p>Perl normally buffers output so it doesn&#39;t make a system call for every bit of output. By saving up output, it makes fewer expensive system calls. For instance, in this little bit of code, you want to print a dot to the screen for every line you process to watch the progress of your program. Instead of seeing a dot for every line, Perl buffers the output and you have a long wait before you see a row of 50 dots all at once:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> # long wait, then row of dots all at once
while( &lt;&gt; ) {
print &quot;.&quot;;
print &quot;\n&quot; unless ++$count % 50;
#... expensive line processing operations
}</pre>
<p>To get around this, you have to unbuffer the output filehandle, in this case, <code>STDOUT</code>. You can set the special variable <code>$|</code> to a true value (mnemonic: making your filehandles &quot;piping hot&quot;):</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> $|++;
# dot shown immediately
while( &lt;&gt; ) {
print &quot;.&quot;;
print &quot;\n&quot; unless ++$count % 50;
#... expensive line processing operations
}</pre>
<p>The <code>$|</code> is one of the per-filehandle special variables, so each filehandle has its own copy of its value. If you want to merge standard output and standard error for instance, you have to unbuffer each (although STDERR might be unbuffered by default):</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> {
my $previous_default = select(STDOUT); # save previous default
$|++; # autoflush STDOUT
select(STDERR);
$|++; # autoflush STDERR, to be sure
select($previous_default); # restore previous default
}
# now should alternate . and +
while( 1 ) {
sleep 1;
print STDOUT &quot;.&quot;;
print STDERR &quot;+&quot;;
print STDOUT &quot;\n&quot; unless ++$count % 25;
}</pre>
<p>Besides the <code>$|</code> special variable, you can use <code>binmode</code> to give your filehandle a <code>:unix</code> layer, which is unbuffered:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> binmode( STDOUT, &quot;:unix&quot; );
while( 1 ) {
sleep 1;
print &quot;.&quot;;
print &quot;\n&quot; unless ++$count % 50;
}</pre>
<p>For more information on output layers, see the entries for <code>binmode</code> and <a href="https://metacpan.org/module/open">open</a> in <a href="https://metacpan.org/module/perlfunc">perlfunc</a>, and the <a href="https://metacpan.org/module/PerlIO">PerlIO</a> module documentation.</p>
<p>If you are using <a href="https://metacpan.org/module/IO::Handle">IO::Handle</a> or one of its subclasses, you can call the <code>autoflush</code> method to change the settings of the filehandle:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use IO::Handle;
open my( $io_fh ), &quot;&gt;&quot;, &quot;output.txt&quot;;
$io_fh-&gt;autoflush(1);</pre>
<p>The <a href="https://metacpan.org/module/IO::Handle">IO::Handle</a> objects also have a <code>flush</code> method. You can flush the buffer any time you want without auto-buffering</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> $io_fh-&gt;flush;</pre>
<h2 id="How-do-I-change-delete-or-insert-a-line-in-a-file-or-append-to-the-beginning-of-a-file-">How do I change, delete, or insert a line in a file, or append to the beginning of a file? </h2>
<p>(contributed by brian d foy)</p>
<p>The basic idea of inserting, changing, or deleting a line from a text file involves reading and printing the file to the point you want to make the change, making the change, then reading and printing the rest of the file. Perl doesn&#39;t provide random access to lines (especially since the record input separator, <code>$/</code>, is mutable), although modules such as <a href="https://metacpan.org/module/Tie::File">Tie::File</a> can fake it.</p>
<p>A Perl program to do these tasks takes the basic form of opening a file, printing its lines, then closing the file:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $in, &#39;&lt;&#39;, $file or die &quot;Can&#39;t read old file: $!&quot;;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;
while( &lt;$in&gt; ) {
print $out $_;
}
close $out;</pre>
<p>Within that basic form, add the parts that you need to insert, change, or delete lines.</p>
<p>To prepend lines to the beginning, print those lines before you enter the loop that prints the existing lines.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $in, &#39;&lt;&#39;, $file or die &quot;Can&#39;t read old file: $!&quot;;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;
print $out &quot;# Add this line to the top\n&quot;; # &lt;--- HERE&#39;S THE MAGIC
while( &lt;$in&gt; ) {
print $out $_;
}
close $out;</pre>
<p>To change existing lines, insert the code to modify the lines inside the <code>while</code> loop. In this case, the code finds all lowercased versions of &quot;perl&quot; and uppercases them. The happens for every line, so be sure that you&#39;re supposed to do that on every line!</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $in, &#39;&lt;&#39;, $file or die &quot;Can&#39;t read old file: $!&quot;;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;
print $out &quot;# Add this line to the top\n&quot;;
while( &lt;$in&gt; ) {
s/\b(perl)\b/Perl/g;
print $out $_;
}
close $out;</pre>
<p>To change only a particular line, the input line number, <code>$.</code>, is useful. First read and print the lines up to the one you want to change. Next, read the single line you want to change, change it, and print it. After that, read the rest of the lines and print those:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> while( &lt;$in&gt; ) { # print the lines before the change
print $out $_;
last if $. == 4; # line number before change
}
my $line = &lt;$in&gt;;
$line =~ s/\b(perl)\b/Perl/g;
print $out $line;
while( &lt;$in&gt; ) { # print the rest of the lines
print $out $_;
}</pre>
<p>To skip lines, use the looping controls. The <code>next</code> in this example skips comment lines, and the <code>last</code> stops all processing once it encounters either <code>__END__</code> or <code>__DATA__</code>.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> while( &lt;$in&gt; ) {
next if /^\s+#/; # skip comment lines
last if /^__(END|DATA)__$/; # stop at end of code marker
print $out $_;
}</pre>
<p>Do the same sort of thing to delete a particular line by using <code>next</code> to skip the lines you don&#39;t want to show up in the output. This example skips every fifth line:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> while( &lt;$in&gt; ) {
next unless $. % 5;
print $out $_;
}</pre>
<p>If, for some odd reason, you really want to see the whole file at once rather than processing line-by-line, you can slurp it in (as long as you can fit the whole thing in memory!):</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $in, &#39;&lt;&#39;, $file or die &quot;Can&#39;t read old file: $!&quot;
open my $out, &#39;&gt;&#39;, &quot;$file.new&quot; or die &quot;Can&#39;t write new file: $!&quot;;
my @lines = do { local $/; &lt;$in&gt; }; # slurp!
# do your magic here
print $out @lines;</pre>
<p>Modules such as <a href="https://metacpan.org/module/File::Slurp">File::Slurp</a> and <a href="https://metacpan.org/module/Tie::File">Tie::File</a> can help with that too. If you can, however, avoid reading the entire file at once. Perl won&#39;t give that memory back to the operating system until the process finishes.</p>
<p>You can also use Perl one-liners to modify a file in-place. The following changes all &#39;Fred&#39; to &#39;Barney&#39; in <i>inFile.txt</i>, overwriting the file with the new contents. With the <code>-p</code> switch, Perl wraps a <code>while</code> loop around the code you specify with <code>-e</code>, and <code>-i</code> turns on in-place editing. The current line is in <code>$_</code>. With <code>-p</code>, Perl automatically prints the value of <code>$_</code> at the end of the loop. See <a href="https://metacpan.org/module/perlrun">perlrun</a> for more details.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -pi -e &#39;s/Fred/Barney/&#39; inFile.txt</pre>
<p>To make a backup of <code>inFile.txt</code>, give <code>-i</code> a file extension to add:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -pi.bak -e &#39;s/Fred/Barney/&#39; inFile.txt</pre>
<p>To change only the fifth line, you can add a test checking <code>$.</code>, the input line number, then only perform the operation when the test passes:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -pi -e &#39;s/Fred/Barney/ if $. == 5&#39; inFile.txt</pre>
<p>To add lines before a certain line, you can add a line (or lines!) before Perl prints <code>$_</code>:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -pi -e &#39;print &quot;Put before third line\n&quot; if $. == 3&#39; inFile.txt</pre>
<p>You can even add a line to the beginning of a file, since the current line prints at the end of the loop:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -pi -e &#39;print &quot;Put before first line\n&quot; if $. == 1&#39; inFile.txt</pre>
<p>To insert a line after one already in the file, use the <code>-n</code> switch. It&#39;s just like <code>-p</code> except that it doesn&#39;t print <code>$_</code> at the end of the loop, so you have to do that yourself. In this case, print <code>$_</code> first, then print the line that you want to add.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -ni -e &#39;print; print &quot;Put after fifth line\n&quot; if $. == 5&#39; inFile.txt</pre>
<p>To delete lines, only print the ones that you want.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -ni -e &#39;print unless /d/&#39; inFile.txt
... or ...
perl -pi -e &#39;next unless /d/&#39; inFile.txt</pre>
<h2 id="How-do-I-count-the-number-of-lines-in-a-file-">How do I count the number of lines in a file? </h2>
<p>(contributed by brian d foy)</p>
<p>Conceptually, the easiest way to count the lines in a file is to simply read them and count them:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $count = 0;
while( &lt;$fh&gt; ) { $count++; }</pre>
<p>You don&#39;t really have to count them yourself, though, since Perl already does that with the <code>$.</code> variable, which is the current line number from the last filehandle read:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> 1 while( &lt;$fh&gt; );
my $count = $.;</pre>
<p>If you want to use <code>$.</code>, you can reduce it to a simple one-liner, like one of these:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> % perl -lne &#39;} print $.; {&#39; file
% perl -lne &#39;END { print $. }&#39; file</pre>
<p>Those can be rather inefficient though. If they aren&#39;t fast enough for you, you might just read chunks of data and count the number of newlines:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $lines = 0;
open my($fh), &#39;&lt;:raw&#39;, $filename or die &quot;Can&#39;t open $filename: $!&quot;;
while( sysread $fh, $buffer, 4096 ) {
$lines += ( $buffer =~ tr/\n// );
}
close FILE;</pre>
<p>However, that doesn&#39;t work if the line ending isn&#39;t a newline. You might change that <code>tr///</code> to a <code>s///</code> so you can count the number of times the input record separator, <code>$/</code>, shows up:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $lines = 0;
open my($fh), &#39;&lt;:raw&#39;, $filename or die &quot;Can&#39;t open $filename: $!&quot;;
while( sysread $fh, $buffer, 4096 ) {
$lines += ( $buffer =~ s|$/||g; );
}
close FILE;</pre>
<p>If you don&#39;t mind shelling out, the <code>wc</code> command is usually the fastest, even with the extra interprocess overhead. Ensure that you have an untainted filename though:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> #!perl -T
$ENV{PATH} = undef;
my $lines;
if( $filename =~ /^([0-9a-z_.]+)\z/ ) {
$lines = `/usr/bin/wc -l $1`
chomp $lines;
}</pre>
<h2 id="How-do-I-delete-the-last-N-lines-from-a-file-">How do I delete the last N lines from a file? </h2>
<p>(contributed by brian d foy)</p>
<p>The easiest conceptual solution is to count the lines in the file then start at the beginning and print the number of lines (minus the last N) to a new file.</p>
<p>Most often, the real question is how you can delete the last N lines without making more than one pass over the file, or how to do it without a lot of copying. The easy concept is the hard reality when you might have millions of lines in your file.</p>
<p>One trick is to use <a href="https://metacpan.org/module/File::ReadBackwards">File::ReadBackwards</a>, which starts at the end of the file. That module provides an object that wraps the real filehandle to make it easy for you to move around the file. Once you get to the spot you need, you can get the actual filehandle and work with it as normal. In this case, you get the file position at the end of the last line you want to keep and truncate the file to that point:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::ReadBackwards;
my $filename = &#39;test.txt&#39;;
my $Lines_to_truncate = 2;
my $bw = File::ReadBackwards-&gt;new( $filename )
or die &quot;Could not read backwards in [$filename]: $!&quot;;
my $lines_from_end = 0;
until( $bw-&gt;eof or $lines_from_end == $Lines_to_truncate ) {
print &quot;Got: &quot;, $bw-&gt;readline;
$lines_from_end++;
}
truncate( $filename, $bw-&gt;tell );</pre>
<p>The <a href="https://metacpan.org/module/File::ReadBackwards">File::ReadBackwards</a> module also has the advantage of setting the input record separator to a regular expression.</p>
<p>You can also use the <a href="https://metacpan.org/module/Tie::File">Tie::File</a> module which lets you access the lines through a tied array. You can use normal array operations to modify your file, including setting the last index and using <code>splice</code>.</p>
<h2 id="How-can-I-use-Perls--i-option-from-within-a-program-">How can I use Perl&#39;s <code>-i</code> option from within a program? </h2>
<p><code>-i</code> sets the value of Perl&#39;s <code>$^I</code> variable, which in turn affects the behavior of <code>&lt;&gt;</code>; see <a href="https://metacpan.org/module/perlrun">perlrun</a> for more details. By modifying the appropriate variables directly, you can get the same behavior within a larger program. For example:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> # ...
{
local($^I, @ARGV) = (&#39;.orig&#39;, glob(&quot;*.c&quot;));
while (&lt;&gt;) {
if ($. == 1) {
print &quot;This line should appear at the top of each file\n&quot;;
}
s/\b(p)earl\b/${1}erl/i; # Correct typos, preserving case
print;
close ARGV if eof; # Reset $.
}
}
# $^I and @ARGV return to their old values here</pre>
<p>This block modifies all the <code>.c</code> files in the current directory, leaving a backup of the original data from each file in a new <code>.c.orig</code> file.</p>
<h2 id="How-can-I-copy-a-file-">How can I copy a file? </h2>
<p>(contributed by brian d foy)</p>
<p>Use the <a href="https://metacpan.org/module/File::Copy">File::Copy</a> module. It comes with Perl and can do a true copy across file systems, and it does its magic in a portable fashion.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Copy;
copy( $original, $new_copy ) or die &quot;Copy failed: $!&quot;;</pre>
<p>If you can&#39;t use <a href="https://metacpan.org/module/File::Copy">File::Copy</a>, you&#39;ll have to do the work yourself: open the original file, open the destination file, then print to the destination file as you read the original. You also have to remember to copy the permissions, owner, and group to the new file.</p>
<h2 id="How-do-I-make-a-temporary-file-name-">How do I make a temporary file name? </h2>
<p>If you don&#39;t need to know the name of the file, you can use <code>open()</code> with <code>undef</code> in place of the file name. In Perl 5.8 or later, the <code>open()</code> function creates an anonymous temporary file:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $tmp, &#39;+&gt;&#39;, undef or die $!;</pre>
<p>Otherwise, you can use the File::Temp module.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Temp qw/ tempfile tempdir /;
my $dir = tempdir( CLEANUP =&gt; 1 );
($fh, $filename) = tempfile( DIR =&gt; $dir );
# or if you don&#39;t need to know the filename
my $fh = tempfile( DIR =&gt; $dir );</pre>
<p>The File::Temp has been a standard module since Perl 5.6.1. If you don&#39;t have a modern enough Perl installed, use the <code>new_tmpfile</code> class method from the IO::File module to get a filehandle opened for reading and writing. Use it if you don&#39;t need to know the file&#39;s name:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use IO::File;
my $fh = IO::File-&gt;new_tmpfile()
or die &quot;Unable to make new temporary file: $!&quot;;</pre>
<p>If you&#39;re committed to creating a temporary file by hand, use the process ID and/or the current time-value. If you need to have many temporary files in one process, use a counter:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> BEGIN {
use Fcntl;
my $temp_dir = -d &#39;/tmp&#39; ? &#39;/tmp&#39; : $ENV{TMPDIR} || $ENV{TEMP};
my $base_name = sprintf &quot;%s/%d-%d-0000&quot;, $temp_dir, $$, time;
sub temp_file {
my $fh;
my $count = 0;
until( defined(fileno($fh)) || $count++ &gt; 100 ) {
$base_name =~ s/-(\d+)$/&quot;-&quot; . (1 + $1)/e;
# O_EXCL is required for security reasons.
sysopen $fh, $base_name, O_WRONLY|O_EXCL|O_CREAT;
}
if( defined fileno($fh) ) {
return ($fh, $base_name);
}
else {
return ();
}
}
}</pre>
<h2 id="How-can-I-manipulate-fixed-record-length-files-">How can I manipulate fixed-record-length files? </h2>
<p>The most efficient way is using <a href="https://metacpan.org/module/perlfunc#pack">pack()</a> and <a href="https://metacpan.org/module/perlfunc#unpack">unpack()</a>. This is faster than using <a href="https://metacpan.org/module/perlfunc#substr">substr()</a> when taking many, many strings. It is slower for just a few.</p>
<p>Here is a sample chunk of code to break up and put back together again some fixed-format input lines, in this case from the output of a normal, Berkeley-style ps:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> # sample input line:
# 15158 p5 T 0:00 perl /home/tchrist/scripts/now-what
my $PS_T = &#39;A6 A4 A7 A5 A*&#39;;
open my $ps, &#39;-|&#39;, &#39;ps&#39;;
print scalar &lt;$ps&gt;;
my @fields = qw( pid tt stat time command );
while (&lt;$ps&gt;) {
my %process;
@process{@fields} = unpack($PS_T, $_);
for my $field ( @fields ) {
print &quot;$field: &lt;$process{$field}&gt;\n&quot;;
}
print &#39;line=&#39;, pack($PS_T, @process{@fields} ), &quot;\n&quot;;
}</pre>
<p>We&#39;ve used a hash slice in order to easily handle the fields of each row. Storing the keys in an array makes it easy to operate on them as a group or loop over them with <code>for</code>. It also avoids polluting the program with global variables and using symbolic references.</p>
<h2 id="How-can-I-make-a-filehandle-local-to-a-subroutine-How-do-I-pass-filehandles-between-subroutines-How-do-I-make-an-array-of-filehandles-">How can I make a filehandle local to a subroutine? How do I pass filehandles between subroutines? How do I make an array of filehandles? </h2>
<p>As of perl5.6, open() autovivifies file and directory handles as references if you pass it an uninitialized scalar variable. You can then pass these references just like any other scalar, and use them in the place of named handles.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, $file_name;
open local $fh, $file_name;
print $fh &quot;Hello World!\n&quot;;
process_file( $fh );</pre>
<p>If you like, you can store these filehandles in an array or a hash. If you access them directly, they aren&#39;t simple scalars and you need to give <code>print</code> a little help by placing the filehandle reference in braces. Perl can only figure it out on its own when the filehandle reference is a simple scalar.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my @fhs = ( $fh1, $fh2, $fh3 );
for( $i = 0; $i &lt;= $#fhs; $i++ ) {
print {$fhs[$i]} &quot;just another Perl answer, \n&quot;;
}</pre>
<p>Before perl5.6, you had to deal with various typeglob idioms which you may see in older code.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open FILE, &quot;&gt; $filename&quot;;
process_typeglob( *FILE );
process_reference( \*FILE );
sub process_typeglob { local *FH = shift; print FH &quot;Typeglob!&quot; }
sub process_reference { local $fh = shift; print $fh &quot;Reference!&quot; }</pre>
<p>If you want to create many anonymous handles, you should check out the Symbol or IO::Handle modules.</p>
<h2 id="How-can-I-use-a-filehandle-indirectly-">How can I use a filehandle indirectly? </h2>
<p>An indirect filehandle is the use of something other than a symbol in a place that a filehandle is expected. Here are ways to get indirect filehandles:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> $fh = SOME_FH; # bareword is strict-subs hostile
$fh = &quot;SOME_FH&quot;; # strict-refs hostile; same package only
$fh = *SOME_FH; # typeglob
$fh = \*SOME_FH; # ref to typeglob (bless-able)
$fh = *SOME_FH{IO}; # blessed IO::Handle from *SOME_FH typeglob</pre>
<p>Or, you can use the <code>new</code> method from one of the IO::* modules to create an anonymous filehandle and store that in a scalar variable.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use IO::Handle; # 5.004 or higher
my $fh = IO::Handle-&gt;new();</pre>
<p>Then use any of those as you would a normal filehandle. Anywhere that Perl is expecting a filehandle, an indirect filehandle may be used instead. An indirect filehandle is just a scalar variable that contains a filehandle. Functions like <code>print</code>, <code>open</code>, <code>seek</code>, or the <code>&lt;FH&gt;</code> diamond operator will accept either a named filehandle or a scalar variable containing one:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> ($ifh, $ofh, $efh) = (*STDIN, *STDOUT, *STDERR);
print $ofh &quot;Type it: &quot;;
my $got = &lt;$ifh&gt;
print $efh &quot;What was that: $got&quot;;</pre>
<p>If you&#39;re passing a filehandle to a function, you can write the function in two ways:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sub accept_fh {
my $fh = shift;
print $fh &quot;Sending to indirect filehandle\n&quot;;
}</pre>
<p>Or it can localize a typeglob and use the filehandle directly:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sub accept_fh {
local *FH = shift;
print FH &quot;Sending to localized filehandle\n&quot;;
}</pre>
<p>Both styles work with either objects or typeglobs of real filehandles. (They might also work with strings under some circumstances, but this is risky.)</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> accept_fh(*STDOUT);
accept_fh($handle);</pre>
<p>In the examples above, we assigned the filehandle to a scalar variable before using it. That is because only simple scalar variables, not expressions or subscripts of hashes or arrays, can be used with built-ins like <code>print</code>, <code>printf</code>, or the diamond operator. Using something other than a simple scalar variable as a filehandle is illegal and won&#39;t even compile:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my @fd = (*STDIN, *STDOUT, *STDERR);
print $fd[1] &quot;Type it: &quot;; # WRONG
my $got = &lt;$fd[0]&gt; # WRONG
print $fd[2] &quot;What was that: $got&quot;; # WRONG</pre>
<p>With <code>print</code> and <code>printf</code>, you get around this by using a block and an expression where you would place the filehandle:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> print { $fd[1] } &quot;funny stuff\n&quot;;
printf { $fd[1] } &quot;Pity the poor %x.\n&quot;, 3_735_928_559;
# Pity the poor deadbeef.</pre>
<p>That block is a proper block like any other, so you can put more complicated code there. This sends the message out to one of two places:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $ok = -x &quot;/bin/cat&quot;;
print { $ok ? $fd[1] : $fd[2] } &quot;cat stat $ok\n&quot;;
print { $fd[ 1+ ($ok || 0) ] } &quot;cat stat $ok\n&quot;;</pre>
<p>This approach of treating <code>print</code> and <code>printf</code> like object methods calls doesn&#39;t work for the diamond operator. That&#39;s because it&#39;s a real operator, not just a function with a comma-less argument. Assuming you&#39;ve been storing typeglobs in your structure as we did above, you can use the built-in function named <code>readline</code> to read a record just as <code>&lt;&gt;</code> does. Given the initialization shown above for @fd, this would work, but only because readline() requires a typeglob. It doesn&#39;t work with objects or strings, which might be a bug we haven&#39;t fixed yet.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> $got = readline($fd[0]);</pre>
<p>Let it be noted that the flakiness of indirect filehandles is not related to whether they&#39;re strings, typeglobs, objects, or anything else. It&#39;s the syntax of the fundamental operators. Playing the object game doesn&#39;t help you at all here.</p>
<h2 id="How-can-I-set-up-a-footer-format-to-be-used-with-write-">How can I set up a footer format to be used with write()? </h2>
<p>There&#39;s no builtin way to do this, but <a href="https://metacpan.org/module/perlform">perlform</a> has a couple of techniques to make it possible for the intrepid hacker.</p>
<h2 id="How-can-I-write-into-a-string-">How can I write() into a string? </h2>
<p>(contributed by brian d foy)</p>
<p>If you want to <code>write</code> into a string, you just have to &lt;open&gt; a filehandle to a string, which Perl has been able to do since Perl 5.6:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open FH, &#39;&gt;&#39;, \my $string;
write( FH );</pre>
<p>Since you want to be a good programmer, you probably want to use a lexical filehandle, even though formats are designed to work with bareword filehandles since the default format names take the filehandle name. However, you can control this with some Perl special per-filehandle variables: <code>$^</code>, which names the top-of-page format, and <code>$~</code> which shows the line format. You have to change the default filehandle to set these variables:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my($fh), &#39;&gt;&#39;, \my $string;
{ # set per-filehandle variables
my $old_fh = select( $fh );
$~ = &#39;ANIMAL&#39;;
$^ = &#39;ANIMAL_TOP&#39;;
select( $old_fh );
}
format ANIMAL_TOP =
ID Type Name
.
format ANIMAL =
@## @&lt;&lt;&lt; @&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;&lt;
$id, $type, $name
.</pre>
<p>Although write can work with lexical or package variables, whatever variables you use have to scope in the format. That most likely means you&#39;ll want to localize some package variables:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> {
local( $id, $type, $name ) = qw( 12 cat Buster );
write( $fh );
}
print $string;</pre>
<p>There are also some tricks that you can play with <code>formline</code> and the accumulator variable <code>$^A</code>, but you lose a lot of the value of formats since <code>formline</code> won&#39;t handle paging and so on. You end up reimplementing formats when you use them.</p>
<h2 id="How-can-I-open-a-filehandle-to-a-string-">How can I open a filehandle to a string? </h2>
<p>(contributed by Peter J. Holzer, hjp-usenet2@hjp.at)</p>
<p>Since Perl 5.8.0 a file handle referring to a string can be created by calling open with a reference to that string instead of the filename. This file handle can then be used to read from or write to the string:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open(my $fh, &#39;&gt;&#39;, \$string) or die &quot;Could not open string for writing&quot;;
print $fh &quot;foo\n&quot;;
print $fh &quot;bar\n&quot;; # $string now contains &quot;foo\nbar\n&quot;
open(my $fh, &#39;&lt;&#39;, \$string) or die &quot;Could not open string for reading&quot;;
my $x = &lt;$fh&gt;; # $x now contains &quot;foo\n&quot;</pre>
<p>With older versions of Perl, the <a href="https://metacpan.org/module/IO::String">IO::String</a> module provides similar functionality.</p>
<h2 id="How-can-I-output-my-numbers-with-commas-added-">How can I output my numbers with commas added? </h2>
<p>(contributed by brian d foy and Benjamin Goldberg)</p>
<p>You can use <a href="https://metacpan.org/module/Number::Format">Number::Format</a> to separate places in a number. It handles locale information for those of you who want to insert full stops instead (or anything else that they want to use, really).</p>
<p>This subroutine will add commas to your number:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sub commify {
local $_ = shift;
1 while s/^([-+]?\d+)(\d{3})/$1,$2/;
return $_;
}</pre>
<p>This regex from Benjamin Goldberg will add commas to numbers:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> s/(^[-+]?\d+?(?=(?&gt;(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g;</pre>
<p>It is easier to see with comments:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> s/(
^[-+]? # beginning of number.
\d+? # first digits before first comma
(?= # followed by, (but not included in the match) :
(?&gt;(?:\d{3})+) # some positive multiple of three digits.
(?!\d) # an *exact* multiple, not x * 3 + 1 or whatever.
)
| # or:
\G\d{3} # after the last group, get three digits
(?=\d) # but they have to have more digits after them.
)/$1,/xg;</pre>
<h2 id="How-can-I-translate-tildes-in-a-filename-">How can I translate tildes (~) in a filename? </h2>
<p>Use the &lt;&gt; (<code>glob()</code>) operator, documented in <a href="https://metacpan.org/module/perlfunc">perlfunc</a>. Versions of Perl older than 5.6 require that you have a shell installed that groks tildes. Later versions of Perl have this feature built in. The <a href="https://metacpan.org/module/File::KGlob">File::KGlob</a> module (available from CPAN) gives more portable glob functionality.</p>
<p>Within Perl, you may use this directly:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> $filename =~ s{
^ ~ # find a leading tilde
( # save this in $1
[^/] # a non-slash character
* # repeated 0 or more times (0 means me)
)
}{
$1
? (getpwnam($1))[7]
: ( $ENV{HOME} || $ENV{LOGDIR} )
}ex;</pre>
<h2 id="How-come-when-I-open-a-file-read-write-it-wipes-it-out-">How come when I open a file read-write it wipes it out? </h2>
<p>Because you&#39;re using something like this, which truncates the file <i>then</i> gives you read-write access:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, &#39;+&gt;&#39;, &#39;/path/name&#39;; # WRONG (almost always)</pre>
<p>Whoops. You should instead use this, which will fail if the file doesn&#39;t exist:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, &#39;+&lt;&#39;, &#39;/path/name&#39;; # open for update</pre>
<p>Using &quot;&gt;&quot; always clobbers or creates. Using &quot;&lt;&quot; never does either. The &quot;+&quot; doesn&#39;t change this.</p>
<p>Here are examples of many kinds of file opens. Those using <code>sysopen</code> all assume that you&#39;ve pulled in the constants from <a href="https://metacpan.org/module/Fcntl">Fcntl</a>:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use Fcntl;</pre>
<p>To open file for reading:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, &#39;&lt;&#39;, $path or die $!;
sysopen my $fh, $path, O_RDONLY or die $!;</pre>
<p>To open file for writing, create new file if needed or else truncate old file:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, &#39;&gt;&#39;, $path or die $!;
sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT or die $!;
sysopen my $fh, $path, O_WRONLY|O_TRUNC|O_CREAT, 0666 or die $!;</pre>
<p>To open file for writing, create new file, file must not exist:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT or die $!;
sysopen my $fh, $path, O_WRONLY|O_EXCL|O_CREAT, 0666 or die $!;</pre>
<p>To open file for appending, create if necessary:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, &#39;&gt;&gt;&#39; $path or die $!;
sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT or die $!;
sysopen my $fh, $path, O_WRONLY|O_APPEND|O_CREAT, 0666 or die $!;</pre>
<p>To open file for appending, file must exist:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sysopen my $fh, $path, O_WRONLY|O_APPEND or die $!;</pre>
<p>To open file for update, file must exist:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, &#39;+&lt;&#39;, $path or die $!;
sysopen my $fh, $path, O_RDWR or die $!;</pre>
<p>To open file for update, create file if necessary:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sysopen my $fh, $path, O_RDWR|O_CREAT or die $!;
sysopen my $fh, $path, O_RDWR|O_CREAT, 0666 or die $!;</pre>
<p>To open file for update, file must not exist:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT or die $!;
sysopen my $fh, $path, O_RDWR|O_EXCL|O_CREAT, 0666 or die $!;</pre>
<p>To open a file without blocking, creating if necessary:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sysopen my $fh, &#39;/foo/somefile&#39;, O_WRONLY|O_NDELAY|O_CREAT
or die &quot;can&#39;t open /foo/somefile: $!&quot;:</pre>
<p>Be warned that neither creation nor deletion of files is guaranteed to be an atomic operation over NFS. That is, two processes might both successfully create or unlink the same file! Therefore O_EXCL isn&#39;t as exclusive as you might wish.</p>
<p>See also <a href="https://metacpan.org/module/perlopentut">perlopentut</a>.</p>
<h2 id="Why-do-I-sometimes-get-an-Argument-list-too-long-when-I-use-">Why do I sometimes get an &quot;Argument list too long&quot; when I use &lt;*&gt;? </h2>
<p>The <code>&lt;&gt;</code> operator performs a globbing operation (see above). In Perl versions earlier than v5.6.0, the internal glob() operator forks csh(1) to do the actual glob expansion, but csh can&#39;t handle more than 127 items and so gives the error message <code>Argument list too long</code>. People who installed tcsh as csh won&#39;t have this problem, but their users may be surprised by it.</p>
<p>To get around this, either upgrade to Perl v5.6.0 or later, do the glob yourself with readdir() and patterns, or use a module like <a href="https://metacpan.org/module/File::Glob">File::Glob</a>, one that doesn&#39;t use the shell to do globbing.</p>
<h2 id="Is-there-a-leak-bug-in-glob-">Is there a leak/bug in glob()? </h2>
<p>(contributed by brian d foy)</p>
<p>Starting with Perl 5.6.0, <code>glob</code> is implemented internally rather than relying on an external resource. As such, memory issues with <code>glob</code> aren&#39;t a problem in modern perls.</p>
<h2 id="How-can-I-open-a-file-with-a-leading-or-trailing-blanks-">How can I open a file with a leading &quot;&gt;&quot; or trailing blanks? </h2>
<p>(contributed by Brian McCauley)</p>
<p>The special two-argument form of Perl&#39;s open() function ignores trailing blanks in filenames and infers the mode from certain leading characters (or a trailing &quot;|&quot;). In older versions of Perl this was the only version of open() and so it is prevalent in old code and books.</p>
<p>Unless you have a particular reason to use the two-argument form you should use the three-argument form of open() which does not treat any characters in the filename as special.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $fh, &quot;&lt;&quot;, &quot; file &quot;; # filename is &quot; file &quot;
open my $fh, &quot;&gt;&quot;, &quot;&gt;file&quot;; # filename is &quot;&gt;file&quot;</pre>
<h2 id="How-can-I-reliably-rename-a-file-">How can I reliably rename a file? </h2>
<p>If your operating system supports a proper mv(1) utility or its functional equivalent, this works:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> rename($old, $new) or system(&quot;mv&quot;, $old, $new);</pre>
<p>It may be more portable to use the <a href="https://metacpan.org/module/File::Copy">File::Copy</a> module instead. You just copy to the new file to the new name (checking return values), then delete the old one. This isn&#39;t really the same semantically as a <code>rename()</code>, which preserves meta-information like permissions, timestamps, inode info, etc.</p>
<h2 id="How-can-I-lock-a-file-">How can I lock a file? </h2>
<p>Perl&#39;s builtin flock() function (see <a href="https://metacpan.org/module/perlfunc">perlfunc</a> for details) will call flock(2) if that exists, fcntl(2) if it doesn&#39;t (on perl version 5.004 and later), and lockf(3) if neither of the two previous system calls exists. On some systems, it may even use a different form of native locking. Here are some gotchas with Perl&#39;s flock():</p>
<ol>
<li><p>Produces a fatal error if none of the three system calls (or their close equivalent) exists.</p>
</li>
<li><p>lockf(3) does not provide shared locking, and requires that the filehandle be open for writing (or appending, or read/writing).</p>
</li>
<li><p>Some versions of flock() can&#39;t lock files over a network (e.g. on NFS file systems), so you&#39;d need to force the use of fcntl(2) when you build Perl. But even this is dubious at best. See the flock entry of <a href="https://metacpan.org/module/perlfunc">perlfunc</a> and the <i>INSTALL</i> file in the source distribution for information on building Perl to do this.</p>
<p>Two potentially non-obvious but traditional flock semantics are that it waits indefinitely until the lock is granted, and that its locks are <i>merely advisory</i>. Such discretionary locks are more flexible, but offer fewer guarantees. This means that files locked with flock() may be modified by programs that do not also use flock(). Cars that stop for red lights get on well with each other, but not with cars that don&#39;t stop for red lights. See the perlport manpage, your port&#39;s specific documentation, or your system-specific local manpages for details. It&#39;s best to assume traditional behavior if you&#39;re writing portable programs. (If you&#39;re not, you should as always feel perfectly free to write for your own system&#39;s idiosyncrasies (sometimes called &quot;features&quot;). Slavish adherence to portability concerns shouldn&#39;t get in the way of your getting your job done.)</p>
<p>For more information on file locking, see also <a href="https://metacpan.org/module/perlopentut#File-Locking">&quot;File Locking&quot; in perlopentut</a> if you have it (new for 5.6).</p>
</li>
</ol>
<h2 id="Why-cant-I-just-open-FH-file.lock-">Why can&#39;t I just open(FH, &quot;&gt;file.lock&quot;)? </h2>
<p>A common bit of code <b>NOT TO USE</b> is this:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sleep(3) while -e &#39;file.lock&#39;; # PLEASE DO NOT USE
open my $lock, &#39;&gt;&#39;, &#39;file.lock&#39;; # THIS BROKEN CODE</pre>
<p>This is a classic race condition: you take two steps to do something which must be done in one. That&#39;s why computer hardware provides an atomic test-and-set instruction. In theory, this &quot;ought&quot; to work:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sysopen my $fh, &quot;file.lock&quot;, O_WRONLY|O_EXCL|O_CREAT
or die &quot;can&#39;t open file.lock: $!&quot;;</pre>
<p>except that lamentably, file creation (and deletion) is not atomic over NFS, so this won&#39;t work (at least, not every time) over the net. Various schemes involving link() have been suggested, but these tend to involve busy-wait, which is also less than desirable.</p>
<h2 id="I-still-dont-get-locking.-I-just-want-to-increment-the-number-in-the-file.-How-can-I-do-this-">I still don&#39;t get locking. I just want to increment the number in the file. How can I do this? </h2>
<p>Didn&#39;t anyone ever tell you web-page hit counters were useless? They don&#39;t count number of hits, they&#39;re a waste of time, and they serve only to stroke the writer&#39;s vanity. It&#39;s better to pick a random number; they&#39;re more realistic.</p>
<p>Anyway, this is what you can do if you can&#39;t help yourself.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use Fcntl qw(:DEFAULT :flock);
sysopen my $fh, &quot;numfile&quot;, O_RDWR|O_CREAT or die &quot;can&#39;t open numfile: $!&quot;;
flock $fh, LOCK_EX or die &quot;can&#39;t flock numfile: $!&quot;;
my $num = &lt;$fh&gt; || 0;
seek $fh, 0, 0 or die &quot;can&#39;t rewind numfile: $!&quot;;
truncate $fh, 0 or die &quot;can&#39;t truncate numfile: $!&quot;;
(print $fh $num+1, &quot;\n&quot;) or die &quot;can&#39;t write numfile: $!&quot;;
close $fh or die &quot;can&#39;t close numfile: $!&quot;;</pre>
<p>Here&#39;s a much better web-page hit counter:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> $hits = int( (time() - 850_000_000) / rand(1_000) );</pre>
<p>If the count doesn&#39;t impress your friends, then the code might. :-)</p>
<h2 id="All-I-want-to-do-is-append-a-small-amount-of-text-to-the-end-of-a-file.-Do-I-still-have-to-use-locking-">All I want to do is append a small amount of text to the end of a file. Do I still have to use locking? </h2>
<p>If you are on a system that correctly implements <code>flock</code> and you use the example appending code from &quot;perldoc -f flock&quot; everything will be OK even if the OS you are on doesn&#39;t implement append mode correctly (if such a system exists). So if you are happy to restrict yourself to OSs that implement <code>flock</code> (and that&#39;s not really much of a restriction) then that is what you should do.</p>
<p>If you know you are only going to use a system that does correctly implement appending (i.e. not Win32) then you can omit the <code>seek</code> from the code in the previous answer.</p>
<p>If you know you are only writing code to run on an OS and filesystem that does implement append mode correctly (a local filesystem on a modern Unix for example), and you keep the file in block-buffered mode and you write less than one buffer-full of output between each manual flushing of the buffer then each bufferload is almost guaranteed to be written to the end of the file in one chunk without getting intermingled with anyone else&#39;s output. You can also use the <code>syswrite</code> function which is simply a wrapper around your system&#39;s <code>write(2)</code> system call.</p>
<p>There is still a small theoretical chance that a signal will interrupt the system-level <code>write()</code> operation before completion. There is also a possibility that some STDIO implementations may call multiple system level <code>write()</code>s even if the buffer was empty to start. There may be some systems where this probability is reduced to zero, and this is not a concern when using <code>:perlio</code> instead of your system&#39;s STDIO.</p>
<h2 id="How-do-I-randomly-update-a-binary-file-">How do I randomly update a binary file? </h2>
<p>If you&#39;re just trying to patch a binary, in many cases something as simple as this works:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> perl -i -pe &#39;s{window manager}{window mangler}g&#39; /usr/bin/emacs</pre>
<p>However, if you have fixed sized records, then you might do something more like this:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $RECSIZE = 220; # size of record, in bytes
my $recno = 37; # which record to update
open my $fh, &#39;+&lt;&#39;, &#39;somewhere&#39; or die &quot;can&#39;t update somewhere: $!&quot;;
seek $fh, $recno * $RECSIZE, 0;
read $fh, $record, $RECSIZE == $RECSIZE or die &quot;can&#39;t read record $recno: $!&quot;;
# munge the record
seek $fh, -$RECSIZE, 1;
print $fh $record;
close $fh;</pre>
<p>Locking and error checking are left as an exercise for the reader. Don&#39;t forget them or you&#39;ll be quite sorry.</p>
<h2 id="How-do-I-get-a-files-timestamp-in-perl-">How do I get a file&#39;s timestamp in perl? </h2>
<p>If you want to retrieve the time at which the file was last read, written, or had its meta-data (owner, etc) changed, you use the <b>-A</b>, <b>-M</b>, or <b>-C</b> file test operations as documented in <a href="https://metacpan.org/module/perlfunc">perlfunc</a>. These retrieve the age of the file (measured against the start-time of your program) in days as a floating point number. Some platforms may not have all of these times. See <a href="https://metacpan.org/module/perlport">perlport</a> for details. To retrieve the &quot;raw&quot; time in seconds since the epoch, you would call the stat function, then use <code>localtime()</code>, <code>gmtime()</code>, or <code>POSIX::strftime()</code> to convert this into human-readable form.</p>
<p>Here&#39;s an example:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $write_secs = (stat($file))[9];
printf &quot;file %s updated at %s\n&quot;, $file,
scalar localtime($write_secs);</pre>
<p>If you prefer something more legible, use the File::stat module (part of the standard distribution in version 5.004 and later):</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> # error checking left as an exercise for reader.
use File::stat;
use Time::localtime;
my $date_string = ctime(stat($file)-&gt;mtime);
print &quot;file $file updated at $date_string\n&quot;;</pre>
<p>The POSIX::strftime() approach has the benefit of being, in theory, independent of the current locale. See <a href="https://metacpan.org/module/perllocale">perllocale</a> for details.</p>
<h2 id="How-do-I-set-a-files-timestamp-in-perl-">How do I set a file&#39;s timestamp in perl? </h2>
<p>You use the utime() function documented in <a href="https://metacpan.org/module/perlfunc#utime">&quot;utime&quot; in perlfunc</a>. By way of example, here&#39;s a little program that copies the read and write times from its first argument to all the rest of them.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> if (@ARGV &lt; 2) {
die &quot;usage: cptimes timestamp_file other_files ...\n&quot;;
}
my $timestamp = shift;
my($atime, $mtime) = (stat($timestamp))[8,9];
utime $atime, $mtime, @ARGV;</pre>
<p>Error checking is, as usual, left as an exercise for the reader.</p>
<p>The perldoc for utime also has an example that has the same effect as touch(1) on files that <i>already exist</i>.</p>
<p>Certain file systems have a limited ability to store the times on a file at the expected level of precision. For example, the FAT and HPFS filesystem are unable to create dates on files with a finer granularity than two seconds. This is a limitation of the filesystems, not of utime().</p>
<h2 id="How-do-I-print-to-more-than-one-file-at-once-">How do I print to more than one file at once? </h2>
<p>To connect one filehandle to several output filehandles, you can use the <a href="https://metacpan.org/module/IO::Tee">IO::Tee</a> or <a href="https://metacpan.org/module/Tie::FileHandle::Multiplex">Tie::FileHandle::Multiplex</a> modules.</p>
<p>If you only have to do this once, you can print individually to each filehandle.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> for my $fh ($fh1, $fh2, $fh3) { print $fh &quot;whatever\n&quot; }</pre>
<h2 id="How-can-I-read-in-an-entire-file-all-at-once-">How can I read in an entire file all at once? </h2>
<p>The customary Perl approach for processing all the lines in a file is to do so one line at a time:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $input, &#39;&lt;&#39;, $file or die &quot;can&#39;t open $file: $!&quot;;
while (&lt;$input&gt;) {
chomp;
# do something with $_
}
close $input or die &quot;can&#39;t close $file: $!&quot;;</pre>
<p>This is tremendously more efficient than reading the entire file into memory as an array of lines and then processing it one element at a time, which is often--if not almost always--the wrong approach. Whenever you see someone do this:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my @lines = &lt;INPUT&gt;;</pre>
<p>You should think long and hard about why you need everything loaded at once. It&#39;s just not a scalable solution.</p>
<p>If you &quot;mmap&quot; the file with the File::Map module from CPAN, you can virtually load the entire file into a string without actually storing it in memory:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Map qw(map_file);
map_file my $string, $filename;</pre>
<p>Once mapped, you can treat <code>$string</code> as you would any other string. Since you don&#39;t necessarily have to load the data, mmap-ing can be very fast and may not increase your memory footprint.</p>
<p>You might also find it more fun to use the standard <a href="https://metacpan.org/module/Tie::File">Tie::File</a> module, or the <a href="https://metacpan.org/module/DB_File">DB_File</a> module&#39;s <code>$DB_RECNO</code> bindings, which allow you to tie an array to a file so that accessing an element of the array actually accesses the corresponding line in the file.</p>
<p>If you want to load the entire file, you can use the <a href="https://metacpan.org/module/File::Slurp">File::Slurp</a> module to do it in one one simple and efficient step:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Slurp;
my $all_of_it = read_file($filename); # entire file in scalar
my @all_lines = read_file($filename); # one line per element</pre>
<p>Or you can read the entire file contents into a scalar like this:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $var;
{
local $/;
open my $fh, &#39;&lt;&#39;, $file or die &quot;can&#39;t open $file: $!&quot;;
$var = &lt;$fh&gt;;
}</pre>
<p>That temporarily undefs your record separator, and will automatically close the file at block exit. If the file is already open, just use this:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $var = do { local $/; &lt;$fh&gt; };</pre>
<p>You can also use a localized <code>@ARGV</code> to eliminate the <code>open</code>:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $var = do { local( @ARGV, $/ ) = $file; &lt;&gt; };</pre>
<p>For ordinary files you can also use the <code>read</code> function.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> read( $fh, $var, -s $fh );</pre>
<p>That third argument tests the byte size of the data on the <code>$fh</code> filehandle and reads that many bytes into the buffer <code>$var</code>.</p>
<h2 id="How-can-I-read-in-a-file-by-paragraphs-">How can I read in a file by paragraphs? </h2>
<p>Use the <code>$/</code> variable (see <a href="https://metacpan.org/module/perlvar">perlvar</a> for details). You can either set it to <code>&quot;&quot;</code> to eliminate empty paragraphs (<code>&quot;abc\n\n\n\ndef&quot;</code>, for instance, gets treated as two paragraphs and not three), or <code>&quot;\n\n&quot;</code> to accept empty paragraphs.</p>
<p>Note that a blank line must have no blanks in it. Thus <span style="white-space: nowrap;"><code>&quot;fred\n \nstuff\n\n&quot;</code></span> is one paragraph, but <code>&quot;fred\n\nstuff\n\n&quot;</code> is two.</p>
<h2 id="How-can-I-read-a-single-character-from-a-file-From-the-keyboard-">How can I read a single character from a file? From the keyboard? </h2>
<p>You can use the builtin <code>getc()</code> function for most filehandles, but it won&#39;t (easily) work on a terminal device. For STDIN, either use the Term::ReadKey module from CPAN or use the sample code in <a href="https://metacpan.org/module/perlfunc#getc">&quot;getc&quot; in perlfunc</a>.</p>
<p>If your system supports the portable operating system programming interface (POSIX), you can use the following code, which you&#39;ll note turns off echo processing as well.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> #!/usr/bin/perl -w
use strict;
$| = 1;
for (1..4) {
print &quot;gimme: &quot;;
my $got = getone();
print &quot;--&gt; $got\n&quot;;
}
exit;
BEGIN {
use POSIX qw(:termios_h);
my ($term, $oterm, $echo, $noecho, $fd_stdin);
my $fd_stdin = fileno(STDIN);
$term = POSIX::Termios-&gt;new();
$term-&gt;getattr($fd_stdin);
$oterm = $term-&gt;getlflag();
$echo = ECHO | ECHOK | ICANON;
$noecho = $oterm &amp; ~$echo;
sub cbreak {
$term-&gt;setlflag($noecho);
$term-&gt;setcc(VTIME, 1);
$term-&gt;setattr($fd_stdin, TCSANOW);
}
sub cooked {
$term-&gt;setlflag($oterm);
$term-&gt;setcc(VTIME, 0);
$term-&gt;setattr($fd_stdin, TCSANOW);
}
sub getone {
my $key = &#39;&#39;;
cbreak();
sysread(STDIN, $key, 1);
cooked();
return $key;
}
}
END { cooked() }</pre>
<p>The Term::ReadKey module from CPAN may be easier to use. Recent versions include also support for non-portable systems as well.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use Term::ReadKey;
open my $tty, &#39;&lt;&#39;, &#39;/dev/tty&#39;;
print &quot;Gimme a char: &quot;;
ReadMode &quot;raw&quot;;
my $key = ReadKey 0, $tty;
ReadMode &quot;normal&quot;;
printf &quot;\nYou said %s, char number %03d\n&quot;,
$key, ord $key;</pre>
<h2 id="How-can-I-tell-whether-theres-a-character-waiting-on-a-filehandle-">How can I tell whether there&#39;s a character waiting on a filehandle?</h2>
<p>The very first thing you should do is look into getting the Term::ReadKey extension from CPAN. As we mentioned earlier, it now even has limited support for non-portable (read: not open systems, closed, proprietary, not POSIX, not Unix, etc.) systems.</p>
<p>You should also check out the Frequently Asked Questions list in comp.unix.* for things like this: the answer is essentially the same. It&#39;s very system-dependent. Here&#39;s one solution that works on BSD systems:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> sub key_ready {
my($rin, $nfd);
vec($rin, fileno(STDIN), 1) = 1;
return $nfd = select($rin,undef,undef,0);
}</pre>
<p>If you want to find out how many characters are waiting, there&#39;s also the FIONREAD ioctl call to be looked at. The <i>h2ph</i> tool that comes with Perl tries to convert C include files to Perl code, which can be <code>require</code>d. FIONREAD ends up defined as a function in the <i>sys/ioctl.ph</i> file:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> require &#39;sys/ioctl.ph&#39;;
$size = pack(&quot;L&quot;, 0);
ioctl(FH, FIONREAD(), $size) or die &quot;Couldn&#39;t call ioctl: $!\n&quot;;
$size = unpack(&quot;L&quot;, $size);</pre>
<p>If <i>h2ph</i> wasn&#39;t installed or doesn&#39;t work for you, you can <i>grep</i> the include files by hand:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> % grep FIONREAD /usr/include/*/*
/usr/include/asm/ioctls.h:#define FIONREAD 0x541B</pre>
<p>Or write a small C program using the editor of champions:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> % cat &gt; fionread.c
#include &lt;sys/ioctl.h&gt;
main() {
printf(&quot;%#08x\n&quot;, FIONREAD);
}
^D
% cc -o fionread fionread.c
% ./fionread
0x4004667f</pre>
<p>And then hard-code it, leaving porting as an exercise to your successor.</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> $FIONREAD = 0x4004667f; # XXX: opsys dependent
$size = pack(&quot;L&quot;, 0);
ioctl(FH, $FIONREAD, $size) or die &quot;Couldn&#39;t call ioctl: $!\n&quot;;
$size = unpack(&quot;L&quot;, $size);</pre>
<p>FIONREAD requires a filehandle connected to a stream, meaning that sockets, pipes, and tty devices work, but <i>not</i> files.</p>
<h2 id="How-do-I-do-a-tail--f-in-perl-">How do I do a <code>tail -f</code> in perl? </h2>
<p>First try</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> seek($gw_fh, 0, 1);</pre>
<p>The statement <code>seek($gw_fh, 0, 1)</code> doesn&#39;t change the current position, but it does clear the end-of-file condition on the handle, so that the next <code>&lt;$gw_fh&gt;</code> makes Perl try again to read something.</p>
<p>If that doesn&#39;t work (it relies on features of your stdio implementation), then you need something more like this:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> for (;;) {
for ($curpos = tell($gw_fh); &lt;$gw_fh&gt;; $curpos =tell($gw_fh)) {
# search for some stuff and put it into files
}
# sleep for a while
seek($gw_fh, $curpos, 0); # seek to where we had been
}</pre>
<p>If this still doesn&#39;t work, look into the <code>clearerr</code> method from <a href="https://metacpan.org/module/IO::Handle">IO::Handle</a>, which resets the error and end-of-file states on the handle.</p>
<p>There&#39;s also a <a href="https://metacpan.org/module/File::Tail">File::Tail</a> module from CPAN.</p>
<h2 id="How-do-I-dup-a-filehandle-in-Perl-">How do I dup() a filehandle in Perl? </h2>
<p>If you check <a href="https://metacpan.org/module/perlfunc#open">&quot;open&quot; in perlfunc</a>, you&#39;ll see that several of the ways to call open() should do the trick. For example:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> open my $log, &#39;&gt;&gt;&#39;, &#39;/foo/logfile&#39;;
open STDERR, &#39;&gt;&amp;&#39;, $log;</pre>
<p>Or even with a literal numeric descriptor:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my $fd = $ENV{MHCONTEXTFD};
open $mhcontext, &quot;&lt;&amp;=$fd&quot;; # like fdopen(3S)</pre>
<p>Note that &quot;&lt;&amp;STDIN&quot; makes a copy, but &quot;&lt;&amp;=STDIN&quot; makes an alias. That means if you close an aliased handle, all aliases become inaccessible. This is not true with a copied one.</p>
<p>Error checking, as always, has been left as an exercise for the reader.</p>
<h2 id="How-do-I-close-a-file-descriptor-by-number-">How do I close a file descriptor by number? </h2>
<p>If, for some reason, you have a file descriptor instead of a filehandle (perhaps you used <code>POSIX::open</code>), you can use the <code>close()</code> function from the <a href="https://metacpan.org/module/POSIX">POSIX</a> module:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use POSIX ();
POSIX::close( $fd );</pre>
<p>This should rarely be necessary, as the Perl <code>close()</code> function is to be used for things that Perl opened itself, even if it was a dup of a numeric descriptor as with <code>MHCONTEXT</code> above. But if you really have to, you may be able to do this:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> require &#39;sys/syscall.ph&#39;;
my $rc = syscall(&amp;SYS_close, $fd + 0); # must force numeric
die &quot;can&#39;t sysclose $fd: $!&quot; unless $rc == -1;</pre>
<p>Or, just use the fdopen(3S) feature of <code>open()</code>:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> {
open my $fh, &quot;&lt;&amp;=$fd&quot; or die &quot;Cannot reopen fd=$fd: $!&quot;;
close $fh;
}</pre>
<h2 id="Why-cant-I-use-C:-temp-foo-in-DOS-paths-Why-doesnt-C:-temp-foo.exe-work-">Why can&#39;t I use &quot;C:\temp\foo&quot; in DOS paths? Why doesn&#39;t `C:\temp\foo.exe` work? </h2>
<p>Whoops! You just put a tab and a formfeed into that filename! Remember that within double quoted strings (&quot;like\this&quot;), the backslash is an escape character. The full list of these is in <a href="https://metacpan.org/module/perlop#Quote-and-Quote-like-Operators">&quot;Quote and Quote-like Operators&quot; in perlop</a>. Unsurprisingly, you don&#39;t have a file called &quot;c:(tab)emp(formfeed)oo&quot; or &quot;c:(tab)emp(formfeed)oo.exe&quot; on your legacy DOS filesystem.</p>
<p>Either single-quote your strings, or (preferably) use forward slashes. Since all DOS and Windows versions since something like MS-DOS 2.0 or so have treated <code>/</code> and <code>\</code> the same in a path, you might as well use the one that doesn&#39;t clash with Perl--or the POSIX shell, ANSI C and C++, awk, Tcl, Java, or Python, just to mention a few. POSIX paths are more portable, too.</p>
<h2 id="Why-doesnt-glob-.-get-all-the-files-">Why doesn&#39;t glob(&quot;*.*&quot;) get all the files? </h2>
<p>Because even on non-Unix ports, Perl&#39;s glob function follows standard Unix globbing semantics. You&#39;ll need <code>glob(&quot;*&quot;)</code> to get all (non-hidden) files. This makes glob() portable even to legacy systems. Your port may include proprietary globbing functions as well. Check its documentation for details.</p>
<h2 id="Why-does-Perl-let-me-delete-read-only-files-Why-does--i-clobber-protected-files-Isnt-this-a-bug-in-Perl-">Why does Perl let me delete read-only files? Why does <code>-i</code> clobber protected files? Isn&#39;t this a bug in Perl?</h2>
<p>This is elaborately and painstakingly described in the <i>file-dir-perms</i> article in the &quot;Far More Than You Ever Wanted To Know&quot; collection in <a href="http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz">http://www.cpan.org/misc/olddoc/FMTEYEWTK.tgz</a> .</p>
<p>The executive summary: learn how your filesystem works. The permissions on a file say what can happen to the data in that file. The permissions on a directory say what can happen to the list of files in that directory. If you delete a file, you&#39;re removing its name from the directory (so the operation depends on the permissions of the directory, not of the file). If you try to write to the file, the permissions of the file govern whether you&#39;re allowed to.</p>
<h2 id="How-do-I-select-a-random-line-from-a-file-">How do I select a random line from a file? </h2>
<p>Short of loading the file into a database or pre-indexing the lines in the file, there are a couple of things that you can do.</p>
<p>Here&#39;s a reservoir-sampling algorithm from the Camel Book:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> srand;
rand($.) &lt; 1 &amp;&amp; ($line = $_) while &lt;&gt;;</pre>
<p>This has a significant advantage in space over reading the whole file in. You can find a proof of this method in <i>The Art of Computer Programming</i>, Volume 2, Section 3.4.2, by Donald E. Knuth.</p>
<p>You can use the <a href="https://metacpan.org/module/File::Random">File::Random</a> module which provides a function for that algorithm:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Random qw/random_line/;
my $line = random_line($filename);</pre>
<p>Another way is to use the <a href="https://metacpan.org/module/Tie::File">Tie::File</a> module, which treats the entire file as an array. Simply access a random array element.</p>
<h2 id="Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines-">Why do I get weird spaces when I print an array of lines?</h2>
<p>(contributed by brian d foy)</p>
<p>If you are seeing spaces between the elements of your array when you print the array, you are probably interpolating the array in double quotes:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my @animals = qw(camel llama alpaca vicuna);
print &quot;animals are: @animals\n&quot;;</pre>
<p>It&#39;s the double quotes, not the <code>print</code>, doing this. Whenever you interpolate an array in a double quote context, Perl joins the elements with spaces (or whatever is in <code>$&quot;</code>, which is a space by default):</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> animals are: camel llama alpaca vicuna</pre>
<p>This is different than printing the array without the interpolation:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> my @animals = qw(camel llama alpaca vicuna);
print &quot;animals are: &quot;, @animals, &quot;\n&quot;;</pre>
<p>Now the output doesn&#39;t have the spaces between the elements because the elements of <code>@animals</code> simply become part of the list to <code>print</code>:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> animals are: camelllamaalpacavicuna</pre>
<p>You might notice this when each of the elements of <code>@array</code> end with a newline. You expect to print one element per line, but notice that every line after the first is indented:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> this is a line
this is another line
this is the third line</pre>
<p>That extra space comes from the interpolation of the array. If you don&#39;t want to put anything between your array elements, don&#39;t use the array in double quotes. You can send it to print without them:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> print @lines;</pre>
<h2 id="How-do-I-traverse-a-directory-tree-">How do I traverse a directory tree?</h2>
<p>(contributed by brian d foy)</p>
<p>The <a href="https://metacpan.org/module/File::Find">File::Find</a> module, which comes with Perl, does all of the hard work to traverse a directory structure. It comes with Perl. You simply call the <code>find</code> subroutine with a callback subroutine and the directories you want to traverse:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Find;
find( \&amp;wanted, @directories );
sub wanted {
# full path in $File::Find::name
# just filename in $_
... do whatever you want to do ...
}</pre>
<p>The <a href="https://metacpan.org/module/File::Find::Closures">File::Find::Closures</a>, which you can download from CPAN, provides many ready-to-use subroutines that you can use with <a href="https://metacpan.org/module/File::Find">File::Find</a>.</p>
<p>The <a href="https://metacpan.org/module/File::Finder">File::Finder</a>, which you can download from CPAN, can help you create the callback subroutine using something closer to the syntax of the <code>find</code> command-line utility:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Find;
use File::Finder;
my $deep_dirs = File::Finder-&gt;depth-&gt;type(&#39;d&#39;)-&gt;ls-&gt;exec(&#39;rmdir&#39;,&#39;{}&#39;);
find( $deep_dirs-&gt;as_options, @places );</pre>
<p>The <a href="https://metacpan.org/module/File::Find::Rule">File::Find::Rule</a> module, which you can download from CPAN, has a similar interface, but does the traversal for you too:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Find::Rule;
my @files = File::Find::Rule-&gt;file()
-&gt;name( &#39;*.pm&#39; )
-&gt;in( @INC );</pre>
<h2 id="How-do-I-delete-a-directory-tree-">How do I delete a directory tree?</h2>
<p>(contributed by brian d foy)</p>
<p>If you have an empty directory, you can use Perl&#39;s built-in <code>rmdir</code>. If the directory is not empty (so, no files or subdirectories), you either have to empty it yourself (a lot of work) or use a module to help you.</p>
<p>The <a href="https://metacpan.org/module/File::Path">File::Path</a> module, which comes with Perl, has a <code>remove_tree</code> which can take care of all of the hard work for you:</p>
<pre class="brush: pl; class-name: 'highlight'; toolbar: false; gutter: false"> use File::Path qw(remove_tree);
remove_tree( @directories );</pre>
<p>The <a href="https://metacpan.org/module/File::Path">File::Path</a> module also has a legacy interface to the older <code>rmtree</code> subroutine.</p>
<h2 id="How-do-I-copy-an-entire-directory-">How do I copy an entire directory?</h2>
<p>(contributed by Shlomi Fish)</p>
<p>To do the equivalent of <code>cp -R</code> (i.e. copy an entire directory tree recursively) in portable Perl, you&#39;ll either need to write something yourself or find a good CPAN module such as <a href="https://metacpan.org/module/File::Copy::Recursive">File::Copy::Recursive</a>.</p>
<h1 id="AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</h1>
<p>Copyright (c) 1997-2010 Tom Christiansen, Nathan Torkington, and other authors as noted. All rights reserved.</p>
<p>This documentation is free; you can redistribute it and/or modify it under the same terms as Perl itself.</p>
<p>Irrespective of its distribution, all code examples here are in the public domain. You are permitted and encouraged to use this code and any derivatives thereof in your own programs for fun or for profit as you see fit. A simple comment in the code giving credit to the FAQ would be courteous but is not required.</p>
<p><em>Version: 5.0150037</em></p></div>
Jump to Line
Something went wrong with that request. Please try again.