1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>perlfaq5 - perldoc.perl.org</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Language" content="en-gb">
<link href="static/css-20090810.css" rel="stylesheet" rev="stylesheet" type="text/css" media="screen">
</head>
<body onLoad="perldoc.startup();" onPageShow="if (event.persisted) perldoc.startup();">
<div id="page">
<div id="header">
<div id="homepage_link">
<a href="index.html"></a>
</div>
<div id="search_form">
<form action="search.html" method="GET" id="search">
<input type="text" name="q" id="search_box" alt="Search">
</form>
</div>
</div>
<div id="body">
<div id="left_column">
<div class="side_group">
<div class="side_panel doc_panel">
<p>Manual</p>
<ul>
<li><a href="index-overview.html">Overview</a>
<li><a href="index-tutorials.html">Tutorials</a>
<li><a href="index-faq.html">FAQs</a>
<li><a href="index-history.html">History / Changes</a>
<li><a href="index-licence.html">License</a>
</ul>
</div>
<div class="side_panel doc_panel">
<p>Reference</p>
<ul>
<li><a href="index-language.html">Language</a>
<li><a href="index-functions.html">Functions</a>
<li><a href="perlop.html">Operators</a>
<li><a href="perlvar.html">Special Variables</a>
<li><a href="index-pragmas.html">Pragmas</a>
<li><a href="index-utilities.html">Utilities</a>
<li><a href="index-internals.html">Internals</a></li>
<li><a href="index-platforms.html">Platform Specific</a>
</ul>
</div>
<div class="side_panel doc_panel">
<p>Modules</p>
<ul>
<li>
<a href="index-modules-A.html">A</a>
•
<a href="index-modules-B.html">B</a>
•
<a href="index-modules-C.html">C</a>
•
<a href="index-modules-D.html">D</a>
•
<a href="index-modules-E.html">E</a>
<li>
<a href="index-modules-F.html">F</a>
•
<a href="index-modules-G.html">G</a>
•
<a href="index-modules-H.html">H</a>
•
<a href="index-modules-I.html">I</a>
•
<a href="index-modules-L.html">L</a>
<li>
<a href="index-modules-M.html">M</a>
•
<a href="index-modules-N.html">N</a>
•
<a href="index-modules-O.html">O</a>
•
<a href="index-modules-P.html">P</a>
•
<a href="index-modules-S.html">S</a>
<li>
<a href="index-modules-T.html">T</a>
•
<a href="index-modules-U.html">U</a>
•
<a href="index-modules-X.html">X</a>
</ul>
</div>
</div>
<div class="side_group">
<div class="side_panel links_panel">
<p>News / Blogs</p>
<ul>
<li><a href="http://perlbuzz.com">Perl Buzz</a></li>
<li><a href="http://ironman.enlightenedperl.org">Perl Iron Man</a></li>
<li><a href="http://perlsphere.net">Perlsphere</a></li>
<li><a href="http://planet.perl.org">Planet Perl</a></li>
<li><a href="http://news.perlfoundation.org/">TPF news</a></li>
<li><a href="http://use.perl.org">Use Perl</a></li>
</ul>
</div>
<div class="side_panel links_panel">
<p>See also</p>
<ul>
<li><a href="http://search.cpan.org">CPAN</a></li>
<li><a href="http://www.perl.org">Perl.org</a></li>
<li><a href="http://www.perl.com">Perl.com</a></li>
<li><a href="http://www.perlfoundation.org/perl5/index.cgi">Perl 5 Wiki</a></li>
<li><a href="http://jobs.perl.org">Perl Jobs</a></li>
<li><a href="http://www.pm.org">Perl Mongers</a></li>
<li><a href="http://www.perlmonks.org">Perl Monks</a></li>
</ul>
</div>
<div class="side_panel links_panel">
<p>Contact</p>
<ul>
<li><a href="http://perl.jonallen.info">Site designed and maintained by Jon Allen (JJ)</a>
<li><a href="http://perl.jonallen.info">http://perl.jonallen.info</a>
</ul>
<ul>
<li><a href="http://perl.jonallen.info/projects/perldoc">View the project page and FAQs</a>
</ul>
</div>
</div>
</div>
<div id="centre_column">
<div id="content_header">
<div id="title_bar">
<div id="page_name">
<h1>perlfaq5</h1>
</div>
<div id="perl_version">
Perl 5 version 10.1 documentation
</div>
<div id="page_links">
<a href="#" onClick="toolbar.goToTop();return false;">Go to top</a>
• <a href="#" id="page_index_toggle">Show page index</a>
</div>
</div>
<div id="breadcrumbs">
<a href="index.html">Home</a> >
<a href="index-faq.html">FAQs</a> >
perlfaq5
</div>
</div>
<div id="content_body">
<!--[if lt IE 7]>
<div class="noscript">
<p>
<strong>It looks like you're using Internet Explorer 6. This is a very old
browser which does not offer full support for modern websites.</strong>
</p>
<p>
Unfortunately this means that this website will not work on
your computer.
</p>
<p>
Don't miss out though! To view the site (and get a better experience from
many other websites), simply upgrade to
<a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet
Explorer 8</a>
or download an alternative browser such as
<a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>,
<a href="http://www.apple.com/safari/download/">Safari</a>, or
<a href="http://www.google.co.uk/chrome">Google Chrome</a>.
</p>
<p>
All of these browsers are free. If you're using a PC at work, you may
need to contact your IT administrator.
</p>
</div>
<![endif]-->
<noscript>
<div class="noscript">
<p>
<strong>Please note: Many features of this site require JavaScript. You appear to have JavaScript disabled,
or are running a non-JavaScript capable web browser.</strong>
</p>
<p>
To get the best experience, please enable JavaScript or download a modern web browser such as <a href="http://www.microsoft.com/windows/Internet-explorer/default.aspx">Internet Explorer 8</a>, <a href="http://www.mozilla.com/en-US/firefox/firefox.html">Firefox</a>, <a href="http://www.apple.com/safari/download/">Safari</a>, or <a href="http://www.google.co.uk/chrome">Google Chrome</a>.
</p>
</div>
</noscript>
<div id="from_search"></div>
<h1>perlfaq5</h1>
<!-- -->
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><ul><li><a href="#How-do-I-flush%2funbuffer-an-output-filehandle%3f--Why-must-I-do-this%3f">How do I flush/unbuffer an output filehandle? Why must I do this?
</a><li><a href="#How-do-I-change%2c-delete%2c-or-insert-a-line-in-a-file%2c-or-append-to-the-beginning-of-a-file%3f">How do I change, delete, or insert a line in a file, or append to the beginning of a file?
</a><li><a href="#How-do-I-count-the-number-of-lines-in-a-file%3f">How do I count the number of lines in a file?
</a><li><a href="#How-can-I-use-Perl's--i-option-from-within-a-program%3f">How can I use Perl's -i option from within a program?
</a><li><a href="#How-can-I-copy-a-file%3f">How can I copy a file?
</a><li><a href="#How-do-I-make-a-temporary-file-name%3f">How do I make a temporary file name?
</a><li><a href="#How-can-I-manipulate-fixed-record-length-files%3f">How can I manipulate fixed-record-length files?
</a><li><a href="#How-can-I-make-a-filehandle-local-to-a-subroutine%3f--How-do-I-pass-filehandles-between-subroutines%3f--How-do-I-make-an-array-of-filehandles%3f">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><a href="#How-can-I-use-a-filehandle-indirectly%3f">How can I use a filehandle indirectly?
</a><li><a href="#How-can-I-set-up-a-footer-format-to-be-used-with-write()%3f">How can I set up a footer format to be used with write()?
</a><li><a href="#How-can-I-write()-into-a-string%3f">How can I write() into a string?
</a><li><a href="#How-can-I-open-a-filehandle-to-a-string%3f">How can I open a filehandle to a string?
</a><li><a href="#How-can-I-output-my-numbers-with-commas-added%3f">How can I output my numbers with commas added?
</a><li><a href="#How-can-I-translate-tildes-(~)-in-a-filename%3f">How can I translate tildes (~) in a filename?
</a><li><a href="#How-come-when-I-open-a-file-read-write-it-wipes-it-out%3f">How come when I open a file read-write it wipes it out?
</a><li><a href="#Why-do-I-sometimes-get-an-%22Argument-list-too-long%22-when-I-use-%3c*%3e%3f">Why do I sometimes get an "Argument list too long" when I use <*>?
</a><li><a href="#Is-there-a-leak%2fbug-in-glob()%3f">Is there a leak/bug in glob()?
</a><li><a href="#How-can-I-open-a-file-with-a-leading-%22%3e%22-or-trailing-blanks%3f">How can I open a file with a leading ">" or trailing blanks?
</a><li><a href="#How-can-I-reliably-rename-a-file%3f">How can I reliably rename a file?
</a><li><a href="#How-can-I-lock-a-file%3f">How can I lock a file?
</a><li><a href="#Why-can't-I-just-open(FH%2c-%22%3efile.lock%22)%3f">Why can't I just open(FH, ">file.lock")?
</a><li><a href="#I-still-don't-get-locking.--I-just-want-to-increment-the-number-in-the-file.--How-can-I-do-this%3f">I still don't get locking. I just want to increment the number in the file. How can I do this?
</a><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%3f">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><a href="#How-do-I-randomly-update-a-binary-file%3f">How do I randomly update a binary file?
</a><li><a href="#How-do-I-get-a-file's-timestamp-in-perl%3f">How do I get a file's timestamp in perl?
</a><li><a href="#How-do-I-set-a-file's-timestamp-in-perl%3f">How do I set a file's timestamp in perl?
</a><li><a href="#How-do-I-print-to-more-than-one-file-at-once%3f">How do I print to more than one file at once?
</a><li><a href="#How-can-I-read-in-an-entire-file-all-at-once%3f">How can I read in an entire file all at once?
</a><li><a href="#How-can-I-read-in-a-file-by-paragraphs%3f">How can I read in a file by paragraphs?
</a><li><a href="#How-can-I-read-a-single-character-from-a-file%3f--From-the-keyboard%3f">How can I read a single character from a file? From the keyboard?
</a><li><a href="#How-can-I-tell-whether-there's-a-character-waiting-on-a-filehandle%3f">How can I tell whether there's a character waiting on a filehandle?</a><li><a href="#How-do-I-do-a-tail--f-in-perl%3f">How do I do a tail -f in perl?
</a><li><a href="#How-do-I-dup()-a-filehandle-in-Perl%3f">How do I dup() a filehandle in Perl?
</a><li><a href="#How-do-I-close-a-file-descriptor-by-number%3f">How do I close a file descriptor by number?
</a><li><a href="#Why-can't-I-use-%22C%3a%5ctemp%5cfoo%22-in-DOS-paths%3f--Why-doesn't-%60C%3a%5ctemp%5cfoo.exe%60-work%3f">Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?
</a><li><a href="#Why-doesn't-glob(%22*.*%22)-get-all-the-files%3f">Why doesn't glob("*.*") get all the files?
</a><li><a href="#Why-does-Perl-let-me-delete-read-only-files%3f--Why-does--i-clobber-protected-files%3f--Isn't-this-a-bug-in-Perl%3f">Why does Perl let me delete read-only files? Why does -i clobber protected files? Isn't this a bug in Perl?</a><li><a href="#How-do-I-select-a-random-line-from-a-file%3f">How do I select a random line from a file?
</a><li><a href="#Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines%3f">Why do I get weird spaces when I print an array of lines?</a><li><a href="#How-do-I-traverse-a-directory-tree%3f">How do I traverse a directory tree?</a><li><a href="#How-do-I-delete-a-directory-tree%3f">How do I delete a directory tree?</a><li><a href="#How-do-I-copy-an-entire-directory%3f">How do I copy an entire directory?</a></ul><li><a href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a></ul><a name="NAME"></a><h1>NAME</h1>
<p>perlfaq5 - Files and Formats</p>
<a name="DESCRIPTION"></a><h1>DESCRIPTION</h1>
<p>This section deals with I/O and the "f" issues: filehandles, flushing,
formats, and footers.</p>
<a name="How-do-I-flush%2funbuffer-an-output-filehandle%3f--Why-must-I-do-this%3f"></a><h2>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's "Suffering From Buffering"
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'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="verbatim"><ol><li> <span class="c"># long wait, then row of dots all at once</span></li><li> while<span class="s">(</span> <> <span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"."</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"\n"</span> unless ++<span class="i">$count</span> % <span class="n">50</span><span class="sc">;</span></li><li></li><li> <span class="c">#... expensive line processing operations</span></li><li> <span class="s">}</span></li></ol></pre><p>To get around this, you have to unbuffer the output filehandle, in this
case, <code class="inline"><span class="w">STDOUT</span></code>
. You can set the special variable <code class="inline"><span class="i">$|</span></code>
to a true value
(mnemonic: making your filehandles "piping hot"):</p>
<pre class="verbatim"><ol><li> <span class="i">$|</span>++<span class="sc">;</span></li><li></li><li> <span class="c"># dot shown immediately</span></li><li> while<span class="s">(</span> <> <span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"."</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"\n"</span> unless ++<span class="i">$count</span> % <span class="n">50</span><span class="sc">;</span></li><li></li><li> <span class="c">#... expensive line processing operations</span></li><li> <span class="s">}</span></li></ol></pre><p>The <code class="inline"><span class="i">$|</span></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="verbatim"><ol><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$previous_default</span> = <a class="l_k" href="functions/select.html">select</a><span class="s">(</span><span class="w">STDOUT</span><span class="s">)</span><span class="sc">;</span> <span class="c"># save previous default</span></li><li> <span class="i">$|</span>++<span class="sc">;</span> <span class="c"># autoflush STDOUT</span></li><li> <a class="l_k" href="functions/select.html">select</a><span class="s">(</span><span class="w">STDERR</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$|</span>++<span class="sc">;</span> <span class="c"># autoflush STDERR, to be sure</span></li><li> <a class="l_k" href="functions/select.html">select</a><span class="s">(</span><span class="i">$previous_default</span><span class="s">)</span><span class="sc">;</span> <span class="c"># restore previous default</span></li><li> <span class="s">}</span></li><li></li><li> <span class="c"># now should alternate . and +</span></li><li> while<span class="s">(</span> <span class="n">1</span> <span class="s">)</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/sleep.html">sleep</a> <span class="n">1</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">STDOUT</span> <span class="q">"."</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">STDERR</span> <span class="q">"+"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">STDOUT</span> <span class="q">"\n"</span> unless ++<span class="i">$count</span> % <span class="n">25</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>Besides the <code class="inline"><span class="i">$|</span></code>
special variable, you can use <code class="inline"><a class="l_k" href="functions/binmode.html">binmode</a></code> to give
your filehandle a <code class="inline"><span class="j">:</span><span class="w">unix</span></code>
layer, which is unbuffered:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/binmode.html">binmode</a><span class="s">(</span> <span class="w">STDOUT</span><span class="cm">,</span> <span class="q">":unix"</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li> while<span class="s">(</span> <span class="n">1</span> <span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/sleep.html">sleep</a> <span class="n">1</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"."</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"\n"</span> unless ++<span class="i">$count</span> % <span class="n">50</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>For more information on output layers, see the entries for <code class="inline"><a class="l_k" href="functions/binmode.html">binmode</a></code>
and <code class="inline"><a class="l_k" href="functions/open.html">open</a></code> in <a href="perlfunc.html">perlfunc</a>, and the <code class="inline"><span class="w">PerlIO</span></code>
module documentation.</p>
<p>If you are using <code class="inline"><span class="w">IO::Handle</span></code>
or one of its subclasses, you can
call the <code class="inline"><span class="w">autoflush</span></code>
method to change the settings of the
filehandle:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Handle</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$io_fh</span> <span class="s">)</span><span class="cm">,</span> <span class="q">">"</span><span class="cm">,</span> <span class="q">"output.txt"</span><span class="sc">;</span></li><li> <span class="i">$io_fh</span><span class="i">->autoflush</span><span class="s">(</span><span class="n">1</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The <code class="inline"><span class="w">IO::Handle</span></code>
objects also have a <code class="inline"><span class="w">flush</span></code>
method. You can flush
the buffer any time you want without auto-buffering</p>
<pre class="verbatim"><ol><li> <span class="i">$io_fh</span><span class="i">->flush</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-change%2c-delete%2c-or-insert-a-line-in-a-file%2c-or-append-to-the-beginning-of-a-file%3f"></a><h2>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't provide random access to lines (especially
since the record input separator, <code class="inline"><span class="i">$/</span></code>
, is mutable), although modules
such as <code class="inline"><span class="w">Tie::File</span></code>
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="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$in</span><span class="cm">,</span> <span class="q">'<'</span><span class="cm">,</span> <span class="i">$file</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't read old file: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$out</span><span class="cm">,</span> <span class="q">'>'</span><span class="cm">,</span> <span class="q">"$file.new"</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't write new file: $!"</span><span class="sc">;</span></li><li></li><li> while<span class="s">(</span> <span class="q"><$in></span> <span class="s">)</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$_</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="i">$out</span><span class="sc">;</span></li></ol></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="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$in</span><span class="cm">,</span> <span class="q">'<'</span><span class="cm">,</span> <span class="i">$file</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't read old file: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$out</span><span class="cm">,</span> <span class="q">'>'</span><span class="cm">,</span> <span class="q">"$file.new"</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't write new file: $!"</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="q">"# Add this line to the top\n"</span><span class="sc">;</span> <span class="c"># <--- HERE'S THE MAGIC</span></li><li></li><li> while<span class="s">(</span> <span class="q"><$in></span> <span class="s">)</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$_</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="i">$out</span><span class="sc">;</span></li></ol></pre><p>To change existing lines, insert the code to modify the lines inside
the <code class="inline">while</code>
loop. In this case, the code finds all lowercased
versions of "perl" and uppercases them. The happens for every line, so
be sure that you're supposed to do that on every line!</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$in</span><span class="cm">,</span> <span class="q">'<'</span><span class="cm">,</span> <span class="i">$file</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't read old file: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$out</span><span class="cm">,</span> <span class="q">'>'</span><span class="cm">,</span> <span class="q">"$file.new"</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't write new file: $!"</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="q">"# Add this line to the top\n"</span><span class="sc">;</span></li><li></li><li> while<span class="s">(</span> <span class="q"><$in></span> <span class="s">)</span></li><li> <span class="s">{</span></li><li> <span class="q">s/\b(perl)\b/Perl/g</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$_</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="i">$out</span><span class="sc">;</span></li></ol></pre><p>To change only a particular line, the input line number, <code class="inline"><span class="i">$.</span></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="verbatim"><ol><li> while<span class="s">(</span> <span class="q"><$in></span> <span class="s">)</span> <span class="c"># print the lines before the change</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$_</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/last.html">last</a> if <span class="i">$.</span> == <span class="n">4</span><span class="sc">;</span> <span class="c"># line number before change</span></li><li> <span class="s">}</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$line</span> = <span class="q"><$in></span><span class="sc">;</span></li><li> <span class="i">$line</span> =~ <span class="q">s/\b(perl)\b/Perl/g</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$line</span><span class="sc">;</span></li><li></li><li> while<span class="s">(</span> <span class="q"><$in></span> <span class="s">)</span> <span class="c"># print the rest of the lines</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$_</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>To skip lines, use the looping controls. The <code class="inline"><a class="l_k" href="functions/next.html">next</a></code> in this example
skips comment lines, and the <code class="inline"><a class="l_k" href="functions/last.html">last</a></code> stops all processing once it
encounters either <code class="inline"><a name="__END__"></a>__END__</code>
or <code class="inline"><a name="__DATA__"></a>__DATA__</code>
.</p>
<pre class="verbatim"><ol><li> while<span class="s">(</span> <span class="q"><$in></span> <span class="s">)</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/next.html">next</a> if <span class="q">/^\s+#/</span><span class="sc">;</span> <span class="c"># skip comment lines</span></li><li> <a class="l_k" href="functions/last.html">last</a> if <span class="q">/^__(END|DATA)__$/</span><span class="sc">;</span> <span class="c"># stop at end of code marker</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$_</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>Do the same sort of thing to delete a particular line by using <code class="inline"><a class="l_k" href="functions/next.html">next</a></code>
to skip the lines you don't want to show up in the output. This
example skips every fifth line:</p>
<pre class="verbatim"><ol><li> while<span class="s">(</span> <span class="q"><$in></span> <span class="s">)</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/next.html">next</a> unless <span class="i">$.</span> % <span class="n">5</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">$_</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></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="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$in</span><span class="cm">,</span> <span class="q">'<'</span><span class="cm">,</span> <span class="i">$file</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't read old file: $!"</span></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$out</span><span class="cm">,</span> <span class="q">'>'</span><span class="cm">,</span> <span class="q">"$file.new"</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't write new file: $!"</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">@lines</span> = <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span> <a class="l_k" href="functions/local.html">local</a> <span class="i">$/</span><span class="sc">;</span> <span class="q"><$in></span> <span class="s">}</span><span class="sc">;</span> <span class="c"># slurp!</span></li><li></li><li> <span class="c"># do your magic here</span></li><li></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$out</span> <span class="i">@lines</span><span class="sc">;</span></li></ol></pre><p>Modules such as <code class="inline"><span class="w">File::Slurp</span></code>
and <code class="inline"><span class="w">Tie::File</span></code>
can help with that
too. If you can, however, avoid reading the entire file at once. Perl
won'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 'Fred' to 'Barney' in <i>inFile.txt</i>, overwriting
the file with the new contents. With the <code class="inline">-p</code>
switch, Perl wraps a
<code class="inline">while</code>
loop around the code you specify with <code class="inline">-e</code>
, and <code class="inline">-<span class="w">i</span></code>
turns
on in-place editing. The current line is in <code class="inline"><span class="i">$_</span></code>
. With <code class="inline">-p</code>
, Perl
automatically prints the value of <code class="inline"><span class="i">$_</span></code>
at the end of the loop. See
<a href="perlrun.html">perlrun</a> for more details.</p>
<pre class="verbatim"><ol><li> perl -pi -e 's/Fred/Barney/' inFile.txt</li></ol></pre><p>To make a backup of <code class="inline"><span class="w">inFile</span>.<span class="w">txt</span></code>
, give <code class="inline">-<span class="w">i</span></code>
a file extension to add:</p>
<pre class="verbatim"><ol><li> perl -pi.bak -e 's/Fred/Barney/' inFile.txt</li></ol></pre><p>To change only the fifth line, you can add a test checking <code class="inline"><span class="i">$.</span></code>
, the
input line number, then only perform the operation when the test
passes:</p>
<pre class="verbatim"><ol><li> perl -pi -e 's/Fred/Barney/ if $. == 5' inFile.txt</li></ol></pre><p>To add lines before a certain line, you can add a line (or lines!)
before Perl prints <code class="inline"><span class="i">$_</span></code>
:</p>
<pre class="verbatim"><ol><li> perl -pi -e 'print "Put before third line\n" if $. == 3' inFile.txt</li></ol></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="verbatim"><ol><li> perl -pi -e 'print "Put before first line\n" if $. == 1' inFile.txt</li></ol></pre><p>To insert a line after one already in the file, use the <code class="inline">-<span class="w">n</span></code>
switch.
It's just like <code class="inline">-p</code>
except that it doesn't print <code class="inline"><span class="i">$_</span></code>
at the end of
the loop, so you have to do that yourself. In this case, print <code class="inline"><span class="i">$_</span></code>
first, then print the line that you want to add.</p>
<pre class="verbatim"><ol><li> perl -ni -e 'print; print "Put after fifth line\n" if $. == 5' inFile.txt</li></ol></pre><p>To delete lines, only print the ones that you want.</p>
<pre class="verbatim"><ol><li> perl -ni -e 'print unless /d/' inFile.txt</li><li></li><li> ... or ...</li><li></li><li> perl -pi -e 'next unless /d/' inFile.txt</li></ol></pre><a name="How-do-I-count-the-number-of-lines-in-a-file%3f"></a><h2>How do I count the number of lines in a file?
</h2>
<p>One fairly efficient way is to count newlines in the file. The
following program uses a feature of tr///, as documented in <a href="perlop.html">perlop</a>.
If your text file doesn't end with a newline, then it's not really a
proper text file, so this may report one fewer line than you expect.</p>
<pre class="verbatim"><ol><li> <span class="i">$lines</span> = <span class="n">0</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FILE</span><span class="cm">,</span> <span class="i">$filename</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Can't open `$filename': $!"</span><span class="sc">;</span></li><li> while <span class="s">(</span><a class="l_k" href="functions/sysread.html">sysread</a> <span class="w">FILE</span><span class="cm">,</span> <span class="i">$buffer</span><span class="cm">,</span> <span class="n">4096</span><span class="s">)</span> <span class="s">{</span></li><li> <span class="i">$lines</span> += <span class="s">(</span><span class="i">$buffer</span> =~ <span class="q">tr/\n//</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="w">FILE</span><span class="sc">;</span></li></ol></pre><p>This assumes no funny games with newline translations.</p>
<a name="How-can-I-use-Perl's--i-option-from-within-a-program%3f"></a><h2>How can I use Perl's <code class="inline">-<span class="w">i</span></code>
option from within a program?
</h2>
<p><code class="inline">-<span class="w">i</span></code>
sets the value of Perl's <code class="inline"><span class="i">$^I</span></code>
variable, which in turn affects
the behavior of <code class="inline"><></code>
; see <a href="perlrun.html">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="verbatim"><ol><li> <span class="c"># ...</span></li><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/local.html">local</a><span class="s">(</span><span class="i">$^I</span><span class="cm">,</span> <span class="i">@ARGV</span><span class="s">)</span> = <span class="s">(</span><span class="q">'.orig'</span><span class="cm">,</span> <a class="l_k" href="functions/glob.html">glob</a><span class="s">(</span><span class="q">"*.c"</span><span class="s">)</span><span class="s">)</span><span class="sc">;</span></li><li> while <span class="s">(</span><><span class="s">)</span> <span class="s">{</span></li><li> if <span class="s">(</span><span class="i">$.</span> == <span class="n">1</span><span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"This line should appear at the top of each file\n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li> <span class="q">s/\b(p)earl\b/${1}erl/i</span><span class="sc">;</span> <span class="c"># Correct typos, preserving case</span></li><li> <a class="l_k" href="functions/print.html">print</a><span class="sc">;</span></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="w">ARGV</span> if <a class="l_k" href="functions/eof.html">eof</a><span class="sc">;</span> <span class="c"># Reset $.</span></li><li> <span class="s">}</span></li><li> <span class="s">}</span></li><li> <span class="c"># $^I and @ARGV return to their old values here</span></li></ol></pre><p>This block modifies all the <code class="inline">.c</code> files in the current directory,
leaving a backup of the original data from each file in a new
<code class="inline">.c.orig</code> file.</p>
<a name="How-can-I-copy-a-file%3f"></a><h2>How can I copy a file?
</h2>
<p>(contributed by brian d foy)</p>
<p>Use the <code class="inline"><span class="w">File::Copy</span></code>
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="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Copy</span><span class="sc">;</span></li><li></li><li> <span class="i">copy</span><span class="s">(</span> <span class="i">$original</span><span class="cm">,</span> <span class="i">$new_copy</span> <span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Copy failed: $!"</span><span class="sc">;</span></li></ol></pre><p>If you can't use <code class="inline"><span class="w">File::Copy</span></code>
, you'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>
<a name="How-do-I-make-a-temporary-file-name%3f"></a><h2>How do I make a temporary file name?
</h2>
<p>If you don't need to know the name of the file, you can use <code class="inline"><a class="l_k" href="functions/open.html">open()</a></code>
with <code class="inline"><a class="l_k" href="functions/undef.html">undef</a></code> in place of the file name. In Perl 5.8 or later, the
<code class="inline"><a class="l_k" href="functions/open.html">open()</a></code> function creates an anonymous temporary file:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$tmp</span><span class="cm">,</span> <span class="q">'+>'</span><span class="cm">,</span> <a class="l_k" href="functions/undef.html">undef</a> or <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>Otherwise, you can use the File::Temp module.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Temp</span> <span class="q">qw/ tempfile tempdir /</span><span class="sc">;</span></li><li></li><li> <span class="i">$dir</span> = <span class="i">tempdir</span><span class="s">(</span> <span class="w">CLEANUP</span> <span class="cm">=></span> <span class="n">1</span> <span class="s">)</span><span class="sc">;</span></li><li> <span class="s">(</span><span class="i">$fh</span><span class="cm">,</span> <span class="i">$filename</span><span class="s">)</span> = <span class="i">tempfile</span><span class="s">(</span> <span class="w">DIR</span> <span class="cm">=></span> <span class="i">$dir</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li> <span class="c"># or if you don't need to know the filename</span></li><li></li><li> <span class="i">$fh</span> = <span class="i">tempfile</span><span class="s">(</span> <span class="w">DIR</span> <span class="cm">=></span> <span class="i">$dir</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The File::Temp has been a standard module since Perl 5.6.1. If you
don't have a modern enough Perl installed, use the <code class="inline"><span class="w">new_tmpfile</span></code>
class method from the IO::File module to get a filehandle opened for
reading and writing. Use it if you don't need to know the file's name:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::File</span><span class="sc">;</span></li><li> <span class="i">$fh</span> = <span class="w">IO::File</span><span class="w">->new_tmpfile</span><span class="s">(</span><span class="s">)</span></li><li> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Unable to make new temporary file: $!"</span><span class="sc">;</span></li></ol></pre><p>If you'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="verbatim"><ol><li> BEGIN <span class="s">{</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Fcntl</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$temp_dir</span> = -d <span class="q">'/tmp'</span> ? <span class="q">'/tmp'</span> <span class="co">:</span> <span class="i">$ENV</span>{<span class="w">TMPDIR</span>} || <span class="i">$ENV</span>{<span class="w">TEMP</span>}<span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$base_name</span> = <a class="l_k" href="functions/sprintf.html">sprintf</a> <span class="q">"%s/%d-%d-0000"</span><span class="cm">,</span> <span class="i">$temp_dir</span><span class="cm">,</span> <span class="i">$$</span><span class="cm">,</span> <a class="l_k" href="functions/time.html">time</a><span class="sc">;</span></li><li></li><li><a name="temp_file"></a> sub <span class="m">temp_file</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/local.html">local</a> <span class="i">*FH</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$count</span> = <span class="n">0</span><span class="sc">;</span></li><li> until<span class="s">(</span> <a class="l_k" href="functions/defined.html">defined</a><span class="s">(</span><a class="l_k" href="functions/fileno.html">fileno</a><span class="s">(</span><span class="w">FH</span><span class="s">)</span><span class="s">)</span> || <span class="i">$count</span>++ > <span class="n">100</span> <span class="s">)</span> <span class="s">{</span></li><li> <span class="i">$base_name</span> =~ <span class="q">s/-(\d+)$/"-" . (1 + $1)/e</span><span class="sc">;</span></li><li> <span class="c"># O_EXCL is required for security reasons.</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a> <span class="w">FH</span><span class="cm">,</span> <span class="i">$base_name</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_EXCL</span>|<span class="w">O_CREAT</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> if<span class="s">(</span> <a class="l_k" href="functions/defined.html">defined</a> <a class="l_k" href="functions/fileno.html">fileno</a><span class="s">(</span><span class="w">FH</span><span class="s">)</span> <span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/return.html">return</a> <span class="s">(</span><span class="i">*FH</span><span class="cm">,</span> <span class="i">$base_name</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li> else <span class="s">{</span></li><li> <a class="l_k" href="functions/return.html">return</a> <span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li> <span class="s">}</span></li><li></li><li> <span class="s">}</span></li></ol></pre><a name="How-can-I-manipulate-fixed-record-length-files%3f"></a><h2>How can I manipulate fixed-record-length files?
</h2>
<p>The most efficient way is using <a href="functions/pack.html">pack</a> and
<a href="functions/unpack.html">unpack</a>. This is faster than using
<a href="functions/substr.html">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="verbatim"><ol><li> <span class="c"># sample input line:</span></li><li> <span class="c"># 15158 p5 T 0:00 perl /home/tchrist/scripts/now-what</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$PS_T</span> = <span class="q">'A6 A4 A7 A5 A*'</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$ps</span><span class="cm">,</span> <span class="q">'-|'</span><span class="cm">,</span> <span class="q">'ps'</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <a class="l_k" href="functions/scalar.html">scalar</a> <span class="q"><$ps></span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">@fields</span> = <span class="q">qw( pid tt stat time command )</span><span class="sc">;</span></li><li> while <span class="s">(</span><span class="q"><$ps></span><span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">%process</span><span class="sc">;</span></li><li> <span class="i">@process</span>{<span class="i">@fields</span>} = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="i">$PS_T</span><span class="cm">,</span> <span class="i">$_</span><span class="s">)</span><span class="sc">;</span></li><li> for <a class="l_k" href="functions/my.html">my</a> <span class="i">$field</span> <span class="s">(</span> <span class="i">@fields</span> <span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"$field: <$process{$field}>\n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">'line='</span><span class="cm">,</span> <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="i">$PS_T</span><span class="cm">,</span> <span class="i">@process</span>{<span class="i">@fields</span>} <span class="s">)</span><span class="cm">,</span> <span class="q">"\n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>We've used a hash slice in order to easily handle the fields of each row.
Storing the keys in an array means it's easy to operate on them as a
group or loop over them with for. It also avoids polluting the program
with global variables and using symbolic references.</p>
<a name="How-can-I-make-a-filehandle-local-to-a-subroutine%3f--How-do-I-pass-filehandles-between-subroutines%3f--How-do-I-make-an-array-of-filehandles%3f"></a><h2>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="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a> <span class="i">$fh</span><span class="cm">,</span> <span class="i">$file_name</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/local.html">local</a> <span class="i">$fh</span><span class="cm">,</span> <span class="i">$file_name</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$fh</span> <span class="q">"Hello World!\n"</span><span class="sc">;</span></li><li></li><li> <span class="i">process_file</span><span class="s">(</span> <span class="i">$fh</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>If you like, you can store these filehandles in an array or a hash.
If you access them directly, they aren't simple scalars and you
need to give <code class="inline"><a class="l_k" href="functions/print.html">print</a></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="verbatim"><ol><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">@fhs</span> = <span class="s">(</span> <span class="i">$fh1</span><span class="cm">,</span> <span class="i">$fh2</span><span class="cm">,</span> <span class="i">$fh3</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li> for<span class="s">(</span> <span class="i">$i</span> = <span class="n">0</span><span class="sc">;</span> <span class="i">$i</span> <= <span class="i">$#fhs</span><span class="sc">;</span> <span class="i">$i</span>++ <span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="s">{</span><span class="i">$fhs</span>[<span class="i">$i</span>]<span class="s">}</span> <span class="q">"just another Perl answer, \n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>Before perl5.6, you had to deal with various typeglob idioms
which you may see in older code.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <span class="w">FILE</span><span class="cm">,</span> <span class="q">"> $filename"</span><span class="sc">;</span></li><li> <span class="i">process_typeglob</span><span class="s">(</span> <span class="i">*FILE</span> <span class="s">)</span><span class="sc">;</span></li><li> <span class="i">process_reference</span><span class="s">(</span> \<span class="i">*FILE</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="process_typeglob"></a> sub <span class="m">process_typeglob</span> <span class="s">{</span> <a class="l_k" href="functions/local.html">local</a> <span class="i">*FH</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span> <a class="l_k" href="functions/print.html">print</a> <span class="i">FH</span> <span class="q">"Typeglob!"</span> <span class="s">}</span></li><li><a name="process_reference"></a> sub <span class="m">process_reference</span> <span class="s">{</span> <a class="l_k" href="functions/local.html">local</a> <span class="i">$fh</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span> <a class="l_k" href="functions/print.html">print</a> <span class="i">$fh</span> <span class="q">"Reference!"</span> <span class="s">}</span></li></ol></pre><p>If you want to create many anonymous handles, you should
check out the Symbol or IO::Handle modules.</p>
<a name="How-can-I-use-a-filehandle-indirectly%3f"></a><h2>How can I use a filehandle indirectly?
</h2>
<p>An indirect filehandle is using something other than a symbol
in a place that a filehandle is expected. Here are ways
to get indirect filehandles:</p>
<pre class="verbatim"><ol><li> <span class="i">$fh</span> = <span class="w">SOME_FH</span><span class="sc">;</span> <span class="c"># bareword is strict-subs hostile</span></li><li> <span class="i">$fh</span> = <span class="q">"SOME_FH"</span><span class="sc">;</span> <span class="c"># strict-refs hostile; same package only</span></li><li> <span class="i">$fh</span> = <span class="i">*SOME_FH</span><span class="sc">;</span> <span class="c"># typeglob</span></li><li> <span class="i">$fh</span> = \<span class="i">*SOME_FH</span><span class="sc">;</span> <span class="c"># ref to typeglob (bless-able)</span></li><li> <span class="i">$fh</span> = <span class="i">*SOME_FH</span>{<span class="w">IO</span>}<span class="sc">;</span> <span class="c"># blessed IO::Handle from *SOME_FH typeglob</span></li></ol></pre><p>Or, you can use the <code class="inline"><span class="w">new</span></code>
method from one of the IO::* modules to
create an anonymous filehandle, store that in a scalar variable,
and use it as though it were a normal filehandle.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">IO::Handle</span><span class="sc">;</span> <span class="c"># 5.004 or higher</span></li><li> <span class="i">$fh</span> = <span class="w">IO::Handle</span><span class="w">->new</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li></ol></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 class="inline"><a class="l_k" href="functions/print.html">print</a></code>, <code class="inline"><a class="l_k" href="functions/open.html">open</a></code>, <code class="inline"><a class="l_k" href="functions/seek.html">seek</a></code>, or
the <code class="inline"><span class="q"><FH></span></code>
diamond operator will accept either a named filehandle
or a scalar variable containing one:</p>
<pre class="verbatim"><ol><li> <span class="s">(</span><span class="i">$ifh</span><span class="cm">,</span> <span class="i">$ofh</span><span class="cm">,</span> <span class="i">$efh</span><span class="s">)</span> = <span class="s">(</span><span class="i">*STDIN</span><span class="cm">,</span> <span class="i">*STDOUT</span><span class="cm">,</span> <span class="i">*STDERR</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$ofh</span> <span class="q">"Type it: "</span><span class="sc">;</span></li><li> <span class="i">$got</span> = <span class="q"><$ifh></span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$efh</span> <span class="q">"What was that: $got"</span><span class="sc">;</span></li></ol></pre><p>If you're passing a filehandle to a function, you can write
the function in two ways:</p>
<pre class="verbatim"><ol><li><a name="accept_fh"></a> sub <span class="m">accept_fh</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$fh</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$fh</span> <span class="q">"Sending to indirect filehandle\n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>Or it can localize a typeglob and use the filehandle directly:</p>
<pre class="verbatim"><ol><li><a name="accept_fh"></a> sub <span class="m">accept_fh</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/local.html">local</a> <span class="i">*FH</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">FH</span> <span class="q">"Sending to localized filehandle\n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></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="verbatim"><ol><li> <span class="i">accept_fh</span><span class="s">(</span><span class="i">*STDOUT</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">accept_fh</span><span class="s">(</span><span class="i">$handle</span><span class="s">)</span><span class="sc">;</span></li></ol></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 class="inline"><a class="l_k" href="functions/print.html">print</a></code>, <code class="inline"><a class="l_k" href="functions/printf.html">printf</a></code>, or the diamond operator. Using
something other than a simple scalar variable as a filehandle is
illegal and won't even compile:</p>
<pre class="verbatim"><ol><li> @fd = (*STDIN, *STDOUT, *STDERR);</li><li> print $fd[1] "Type it: "; # WRONG</li><li> $got = <$fd[0]> # WRONG</li><li> print $fd[2] "What was that: $got"; # WRONG</li></ol></pre><p>With <code class="inline"><a class="l_k" href="functions/print.html">print</a></code> and <code class="inline"><a class="l_k" href="functions/printf.html">printf</a></code>, you get around this by using a block and
an expression where you would place the filehandle:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/print.html">print</a> <span class="s">{</span> <span class="i">$fd</span>[<span class="n">1</span>] <span class="s">}</span> <span class="q">"funny stuff\n"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/printf.html">printf</a> <span class="s">{</span> <span class="i">$fd</span>[<span class="n">1</span>] <span class="s">}</span> <span class="q">"Pity the poor %x.\n"</span><span class="cm">,</span> <span class="n">3_735_928_559</span><span class="sc">;</span></li><li> <span class="c"># Pity the poor deadbeef.</span></li></ol></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="verbatim"><ol><li> <span class="i">$ok</span> = -x <span class="q">"/bin/cat"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="s">{</span> <span class="i">$ok</span> ? <span class="i">$fd</span>[<span class="n">1</span>] <span class="co">:</span> <span class="i">$fd</span>[<span class="n">2</span>] <span class="s">}</span> <span class="q">"cat stat $ok\n"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="s">{</span> <span class="i">$fd</span>[ <span class="n">1</span>+ <span class="s">(</span><span class="i">$ok</span> || <span class="n">0</span><span class="s">)</span> ] <span class="s">}</span> <span class="q">"cat stat $ok\n"</span><span class="sc">;</span></li></ol></pre><p>This approach of treating <code class="inline"><a class="l_k" href="functions/print.html">print</a></code> and <code class="inline"><a class="l_k" href="functions/printf.html">printf</a></code> like object methods
calls doesn't work for the diamond operator. That's because it's a
real operator, not just a function with a comma-less argument. Assuming
you've been storing typeglobs in your structure as we did above, you
can use the built-in function named <code class="inline"><a class="l_k" href="functions/readline.html">readline</a></code> to read a record just
as <code class="inline"><></code>
does. Given the initialization shown above for @fd, this
would work, but only because readline() requires a typeglob. It doesn't
work with objects or strings, which might be a bug we haven't fixed yet.</p>
<pre class="verbatim"><ol><li> <span class="i">$got</span> = <a class="l_k" href="functions/readline.html">readline</a><span class="s">(</span><span class="i">$fd</span>[<span class="n">0</span>]<span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Let it be noted that the flakiness of indirect filehandles is not
related to whether they're strings, typeglobs, objects, or anything else.
It's the syntax of the fundamental operators. Playing the object
game doesn't help you at all here.</p>
<a name="How-can-I-set-up-a-footer-format-to-be-used-with-write()%3f"></a><h2>How can I set up a footer format to be used with write()?
</h2>
<p>There's no builtin way to do this, but <a href="perlform.html">perlform</a> has a couple of
techniques to make it possible for the intrepid hacker.</p>
<a name="How-can-I-write()-into-a-string%3f"></a><h2>How can I write() into a string?
</h2>
<p>See <a href="perlform.html#Accessing-Formatting-Internals">"Accessing Formatting Internals" in perlform</a> for an <code class="inline"><span class="i">swrite</span><span class="s">(</span><span class="s">)</span></code>
function.</p>
<a name="How-can-I-open-a-filehandle-to-a-string%3f"></a><h2>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="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$fh</span><span class="cm">,</span> <span class="q">'>'</span><span class="cm">,</span> \<span class="i">$string</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Could not open string for writing"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$fh</span> <span class="q">"foo\n"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">$fh</span> <span class="q">"bar\n"</span><span class="sc">;</span> <span class="c"># $string now contains "foo\nbar\n"</span></li><li></li><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><a class="l_k" href="functions/my.html">my</a> <span class="i">$fh</span><span class="cm">,</span> <span class="q">'<'</span><span class="cm">,</span> \<span class="i">$string</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Could not open string for reading"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$x</span> = <span class="q"><$fh></span><span class="sc">;</span> <span class="c"># $x now contains "foo\n"</span></li></ol></pre><p>With older versions of Perl, the <code class="inline"><span class="w">IO::String</span></code>
module provides similar
functionality.</p>
<a name="How-can-I-output-my-numbers-with-commas-added%3f"></a><h2>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="http://search.cpan.org/perldoc/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="verbatim"><ol><li><a name="commify"></a> sub <span class="m">commify</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/local.html">local</a> <span class="i">$_</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li> <span class="n">1</span> while <span class="q">s/^([-+]?\d+)(\d{3})/$1,$2/</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/return.html">return</a> <span class="i">$_</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>This regex from Benjamin Goldberg will add commas to numbers:</p>
<pre class="verbatim"><ol><li> <span class="q">s/(^[-+]?\d+?(?=(?>(?:\d{3})+)(?!\d))|\G\d{3}(?=\d))/$1,/g</span><span class="sc">;</span></li></ol></pre><p>It is easier to see with comments:</p>
<pre class="verbatim"><ol><li> <span class="q">s/(</span></li><li> <span class="q"> ^[-+]? # beginning of number.</span></li><li> <span class="q"> \d+? # first digits before first comma</span></li><li> <span class="q"> (?= # followed by, (but not included in the match) :</span></li><li> <span class="q"> (?>(?:\d{3})+) # some positive multiple of three digits.</span></li><li> <span class="q"> (?!\d) # an *exact* multiple, not x * 3 + 1 or whatever.</span></li><li> <span class="q"> )</span></li><li> <span class="q"> | # or:</span></li><li> <span class="q"> \G\d{3} # after the last group, get three digits</span></li><li> <span class="q"> (?=\d) # but they have to have more digits after them.</span></li><li> <span class="q"> )/$1,/xg</span><span class="sc">;</span></li></ol></pre><a name="How-can-I-translate-tildes-(~)-in-a-filename%3f"></a><h2>How can I translate tildes (~) in a filename?
</h2>
<p>Use the <> (<code class="inline"><a class="l_k" href="functions/glob.html">glob()</a></code>) operator, documented in <a href="perlfunc.html">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 <code class="inline"><span class="w">File::KGlob</span></code>
module (available from CPAN) gives more
portable glob functionality.</p>
<p>Within Perl, you may use this directly:</p>
<pre class="verbatim"><ol><li> <span class="i">$filename</span> =~ <span class="q">s{</span></li><li> <span class="q"> ^ ~ # find a leading tilde</span></li><li> <span class="q"> ( # save this in $1</span></li><li> <span class="q"> [^/] # a non-slash character</span></li><li> <span class="q"> * # repeated 0 or more times (0 means me)</span></li><li> <span class="q"> )</span></li><li> <span class="q"> }{</span></li><li> <span class="q"> $1</span></li><li> <span class="q"> ? (getpwnam($1))[7]</span></li><li> <span class="q"> : ( $ENV{HOME} || $ENV{LOGDIR} )</span></li><li> <span class="q"> }ex</span><span class="sc">;</span></li></ol></pre><a name="How-come-when-I-open-a-file-read-write-it-wipes-it-out%3f"></a><h2>How come when I open a file read-write it wipes it out?
</h2>
<p>Because you're using something like this, which truncates the file and
<i>then</i> gives you read-write access:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"+> /path/name"</span><span class="s">)</span><span class="sc">;</span> <span class="c"># WRONG (almost always)</span></li></ol></pre><p>Whoops. You should instead use this, which will fail if the file
doesn't exist.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"+< /path/name"</span><span class="s">)</span><span class="sc">;</span> <span class="c"># open for update</span></li></ol></pre><p>Using ">" always clobbers or creates. Using "<" never does
either. The "+" doesn't change this.</p>
<p>Here are examples of many kinds of file opens. Those using sysopen()
all assume</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Fcntl</span><span class="sc">;</span></li></ol></pre><p>To open file for reading:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"< $path"</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_RDONLY</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open file for writing, create new file if needed or else truncate old file:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"> $path"</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_TRUNC</span>|<span class="w">O_CREAT</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_TRUNC</span>|<span class="w">O_CREAT</span><span class="cm">,</span> <span class="n">0666</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open file for writing, create new file, file must not exist:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_EXCL</span>|<span class="w">O_CREAT</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_EXCL</span>|<span class="w">O_CREAT</span><span class="cm">,</span> <span class="n">0666</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open file for appending, create if necessary:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">">> $path"</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_APPEND</span>|<span class="w">O_CREAT</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_APPEND</span>|<span class="w">O_CREAT</span><span class="cm">,</span> <span class="n">0666</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open file for appending, file must exist:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_APPEND</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open file for update, file must exist:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"+< $path"</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_RDWR</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open file for update, create file if necessary:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_RDWR</span>|<span class="w">O_CREAT</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_RDWR</span>|<span class="w">O_CREAT</span><span class="cm">,</span> <span class="n">0666</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open file for update, file must not exist:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_RDWR</span>|<span class="w">O_EXCL</span>|<span class="w">O_CREAT</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$path</span><span class="cm">,</span> <span class="w">O_RDWR</span>|<span class="w">O_EXCL</span>|<span class="w">O_CREAT</span><span class="cm">,</span> <span class="n">0666</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="i">$!</span><span class="sc">;</span></li></ol></pre><p>To open a file without blocking, creating if necessary:</p>
<pre class="verbatim"><ol><li> sysopen(FH, "/foo/somefile", O_WRONLY|O_NDELAY|O_CREAT)</li><li> or die "can't open /foo/somefile: $!":</li></ol></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't as exclusive as you might wish.</p>
<p>See also the new <a href="perlopentut.html">perlopentut</a> if you have it (new for 5.6).</p>
<a name="Why-do-I-sometimes-get-an-%22Argument-list-too-long%22-when-I-use-%3c*%3e%3f"></a><h2>Why do I sometimes get an "Argument list too long" when I use <*>?
</h2>
<p>The <code class="inline"><></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't handle more than 127 items and so gives the error message
<code class="inline"><span class="w">Argument</span> <span class="w">list</span> <span class="w">too</span> <span class="w">long</span></code>
. People who installed tcsh as csh won'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 File::KGlob,
one that doesn't use the shell to do globbing.</p>
<a name="Is-there-a-leak%2fbug-in-glob()%3f"></a><h2>Is there a leak/bug in glob()?
</h2>
<p>Due to the current implementation on some operating systems, when you
use the glob() function or its angle-bracket alias in a scalar
context, you may cause a memory leak and/or unpredictable behavior. It's
best therefore to use glob() only in list context.</p>
<a name="How-can-I-open-a-file-with-a-leading-%22%3e%22-or-trailing-blanks%3f"></a><h2>How can I open a file with a leading ">" or trailing blanks?
</h2>
<p>(contributed by Brian McCauley)</p>
<p>The special two argument form of Perl's open() function ignores
trailing blanks in filenames and infers the mode from certain leading
characters (or a trailing "|"). 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="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <span class="w">FILE</span><span class="cm">,</span> <span class="q">"<"</span><span class="cm">,</span> <span class="q">" file "</span><span class="sc">;</span> <span class="c"># filename is " file "</span></li><li> <a class="l_k" href="functions/open.html">open</a> <span class="w">FILE</span><span class="cm">,</span> <span class="q">">"</span><span class="cm">,</span> <span class="q">">file"</span><span class="sc">;</span> <span class="c"># filename is ">file"</span></li></ol></pre><a name="How-can-I-reliably-rename-a-file%3f"></a><h2>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="verbatim"><ol><li> <a class="l_k" href="functions/rename.html">rename</a><span class="s">(</span><span class="i">$old</span><span class="cm">,</span> <span class="i">$new</span><span class="s">)</span> or <a class="l_k" href="functions/system.html">system</a><span class="s">(</span><span class="q">"mv"</span><span class="cm">,</span> <span class="i">$old</span><span class="cm">,</span> <span class="i">$new</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>It may be more portable to use the File::Copy module instead.
You just copy to the new file to the new name (checking return
values), then delete the old one. This isn't really the same
semantically as a rename(), which preserves meta-information like
permissions, timestamps, inode info, etc.</p>
<p>Newer versions of File::Copy export a move() function.</p>
<a name="How-can-I-lock-a-file%3f"></a><h2>How can I lock a file?
</h2>
<p>Perl's builtin flock() function (see <a href="perlfunc.html">perlfunc</a> for details) will call
flock(2) if that exists, fcntl(2) if it doesn'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'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't lock files over a network (e.g. on NFS file
systems), so you'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="perlfunc.html">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't
stop for red lights. See the perlport manpage, your port's specific
documentation, or your system-specific local manpages for details. It's
best to assume traditional behavior if you're writing portable programs.
(If you're not, you should as always feel perfectly free to write
for your own system's idiosyncrasies (sometimes called "features").
Slavish adherence to portability concerns shouldn't get in the way of
your getting your job done.)</p>
<p>For more information on file locking, see also
<a href="perlopentut.html#File-Locking">"File Locking" in perlopentut</a> if you have it (new for 5.6).</p>
</li>
</ol>
<a name="Why-can't-I-just-open(FH%2c-%22%3efile.lock%22)%3f"></a><h2>Why can't I just open(FH, ">file.lock")?
</h2>
<p>A common bit of code <b>NOT TO USE</b> is this:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/sleep.html">sleep</a><span class="s">(</span><span class="n">3</span><span class="s">)</span> while -e <span class="q">"file.lock"</span><span class="sc">;</span> <span class="c"># PLEASE DO NOT USE</span></li><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">LCK</span><span class="cm">,</span> <span class="q">"> file.lock"</span><span class="s">)</span><span class="sc">;</span> <span class="c"># THIS BROKEN CODE</span></li></ol></pre><p>This is a classic race condition: you take two steps to do something
which must be done in one. That's why computer hardware provides an
atomic test-and-set instruction. In theory, this "ought" to work:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"file.lock"</span><span class="cm">,</span> <span class="w">O_WRONLY</span>|<span class="w">O_EXCL</span>|<span class="w">O_CREAT</span><span class="s">)</span></li><li> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't open file.lock: $!"</span><span class="sc">;</span></li></ol></pre><p>except that lamentably, file creation (and deletion) is not atomic
over NFS, so this won'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>
<a name="I-still-don't-get-locking.--I-just-want-to-increment-the-number-in-the-file.--How-can-I-do-this%3f"></a><h2>I still don't get locking. I just want to increment the number in the file. How can I do this?
</h2>
<p>Didn't anyone ever tell you web-page hit counters were useless?
They don't count number of hits, they're a waste of time, and they serve
only to stroke the writer's vanity. It's better to pick a random number;
they're more realistic.</p>
<p>Anyway, this is what you can do if you can't help yourself.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Fcntl</span> <span class="q">qw(:DEFAULT :flock)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysopen.html">sysopen</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"numfile"</span><span class="cm">,</span> <span class="w">O_RDWR</span>|<span class="w">O_CREAT</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't open numfile: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/flock.html">flock</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="w">LOCK_EX</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't flock numfile: $!"</span><span class="sc">;</span></li><li> <span class="i">$num</span> = <span class="q"><FH></span> || <span class="n">0</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/seek.html">seek</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't rewind numfile: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/truncate.html">truncate</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't truncate numfile: $!"</span><span class="sc">;</span></li><li> <span class="s">(</span><a class="l_k" href="functions/print.html">print</a> <span class="i">FH</span> <span class="i">$num</span>+<span class="n">1</span><span class="cm">,</span> <span class="q">"\n"</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't write numfile: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="w">FH</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't close numfile: $!"</span><span class="sc">;</span></li></ol></pre><p>Here's a much better web-page hit counter:</p>
<pre class="verbatim"><ol><li> <span class="i">$hits</span> = <a class="l_k" href="functions/int.html">int</a><span class="s">(</span> <span class="s">(</span><a class="l_k" href="functions/time.html">time</a><span class="s">(</span><span class="s">)</span> - <span class="n">850_000_000</span><span class="s">)</span> / <a class="l_k" href="functions/rand.html">rand</a><span class="s">(</span><span class="n">1_000</span><span class="s">)</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>If the count doesn't impress your friends, then the code might. :-)</p>
<a name="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%3f"></a><h2>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 class="inline"><a class="l_k" href="functions/flock.html">flock</a></code> and you use
the example appending code from "perldoc -f flock" everything will be
OK even if the OS you are on doesn't implement append mode correctly
(if such a system exists.) So if you are happy to restrict yourself to
OSs that implement <code class="inline"><a class="l_k" href="functions/flock.html">flock</a></code> (and that'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 class="inline"><a class="l_k" href="functions/seek.html">seek</a></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's output. You can also use the
<code class="inline"><a class="l_k" href="functions/syswrite.html">syswrite</a></code> function which is simply a wrapper around your system's
<code class="inline"><a class="l_k" href="functions/write.html">write(2)</a></code> system call.</p>
<p>There is still a small theoretical chance that a signal will interrupt
the system level <code class="inline"><a class="l_k" href="functions/write.html">write()</a></code> operation before completion. There is also
a possibility that some STDIO implementations may call multiple system
level <code class="inline"><a class="l_k" href="functions/write.html">write()</a></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 class="inline"><span class="j">:</span><span class="w">perlio</span></code>
instead of your system's STDIO.</p>
<a name="How-do-I-randomly-update-a-binary-file%3f"></a><h2>How do I randomly update a binary file?
</h2>
<p>If you're just trying to patch a binary, in many cases something as
simple as this works:</p>
<pre class="verbatim"><ol><li> <span class="w">perl</span> -<span class="w">i</span> -<span class="w">pe</span> <span class="q">'s{window manager}{window mangler}g'</span> /<span class="w">usr</span>/<span class="w">bin</span>/<span class="w">emacs</span></li></ol></pre><p>However, if you have fixed sized records, then you might do something more
like this:</p>
<pre class="verbatim"><ol><li> <span class="i">$RECSIZE</span> = <span class="n">220</span><span class="sc">;</span> <span class="c"># size of record, in bytes</span></li><li> <span class="i">$recno</span> = <span class="n">37</span><span class="sc">;</span> <span class="c"># which record to update</span></li><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="q">"+<somewhere"</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't update somewhere: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/seek.html">seek</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$recno</span> * <span class="i">$RECSIZE</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/read.html">read</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$record</span><span class="cm">,</span> <span class="i">$RECSIZE</span><span class="s">)</span> == <span class="i">$RECSIZE</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't read record $recno: $!"</span><span class="sc">;</span></li><li> <span class="c"># munge the record</span></li><li> <a class="l_k" href="functions/seek.html">seek</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> -<span class="i">$RECSIZE</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">FH</span> <span class="i">$record</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="w">FH</span><span class="sc">;</span></li></ol></pre><p>Locking and error checking are left as an exercise for the reader.
Don't forget them or you'll be quite sorry.</p>
<a name="How-do-I-get-a-file's-timestamp-in-perl%3f"></a><h2>How do I get a file'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="perlfunc.html">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="perlport.html">perlport</a> for details. To
retrieve the "raw" time in seconds since the epoch, you
would call the stat function, then use localtime(),
gmtime(), or POSIX::strftime() to convert this into
human-readable form.</p>
<p>Here's an example:</p>
<pre class="verbatim"><ol><li> <span class="i">$write_secs</span> = <span class="s">(</span><a class="l_k" href="functions/stat.html">stat</a><span class="s">(</span><span class="i">$file</span><span class="s">)</span><span class="s">)</span>[<span class="n">9</span>]<span class="sc">;</span></li><li> <a class="l_k" href="functions/printf.html">printf</a> <span class="q">"file %s updated at %s\n"</span><span class="cm">,</span> <span class="i">$file</span><span class="cm">,</span></li><li> <a class="l_k" href="functions/scalar.html">scalar</a> <a class="l_k" href="functions/localtime.html">localtime</a><span class="s">(</span><span class="i">$write_secs</span><span class="s">)</span><span class="sc">;</span></li></ol></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="verbatim"><ol><li> <span class="c"># error checking left as an exercise for reader.</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::stat</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Time::localtime</span><span class="sc">;</span></li><li> <span class="i">$date_string</span> = <span class="i">ctime</span><span class="s">(</span><a class="l_k" href="functions/stat.html">stat</a><span class="s">(</span><span class="i">$file</span><span class="s">)</span><span class="i">->mtime</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"file $file updated at $date_string\n"</span><span class="sc">;</span></li></ol></pre><p>The POSIX::strftime() approach has the benefit of being,
in theory, independent of the current locale. See <a href="perllocale.html">perllocale</a>
for details.</p>
<a name="How-do-I-set-a-file's-timestamp-in-perl%3f"></a><h2>How do I set a file's timestamp in perl?
</h2>
<p>You use the utime() function documented in <a href="functions/utime.html">utime</a>.
By way of example, here's a little program that copies the
read and write times from its first argument to all the rest
of them.</p>
<pre class="verbatim"><ol><li> if <span class="s">(</span><span class="i">@ARGV</span> < <span class="n">2</span><span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/die.html">die</a> <span class="q">"usage: cptimes timestamp_file other_files ...\n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li> <span class="i">$timestamp</span> = <a class="l_k" href="functions/shift.html">shift</a><span class="sc">;</span></li><li> <span class="s">(</span><span class="i">$atime</span><span class="cm">,</span> <span class="i">$mtime</span><span class="s">)</span> = <span class="s">(</span><a class="l_k" href="functions/stat.html">stat</a><span class="s">(</span><span class="i">$timestamp</span><span class="s">)</span><span class="s">)</span>[<span class="n">8</span><span class="cm">,</span><span class="n">9</span>]<span class="sc">;</span></li><li> <a class="l_k" href="functions/utime.html">utime</a> <span class="i">$atime</span><span class="cm">,</span> <span class="i">$mtime</span><span class="cm">,</span> <span class="i">@ARGV</span><span class="sc">;</span></li></ol></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>
<a name="How-do-I-print-to-more-than-one-file-at-once%3f"></a><h2>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 IO::Tee or Tie::FileHandle::Multiplex modules.</p>
<p>If you only have to do this once, you can print individually
to each filehandle.</p>
<pre class="verbatim"><ol><li> for <span class="i">$fh</span> <span class="s">(</span><span class="w">FH1</span><span class="cm">,</span> <span class="w">FH2</span><span class="cm">,</span> <span class="w">FH3</span><span class="s">)</span> <span class="s">{</span> <a class="l_k" href="functions/print.html">print</a> <span class="i">$fh</span> <span class="q">"whatever\n"</span> <span class="s">}</span></li></ol></pre><a name="How-can-I-read-in-an-entire-file-all-at-once%3f"></a><h2>How can I read in an entire file all at once?
</h2>
<p>You can use the File::Slurp module to do it in one step.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Slurp</span><span class="sc">;</span></li><li></li><li> <span class="i">$all_of_it</span> = <span class="i">read_file</span><span class="s">(</span><span class="i">$filename</span><span class="s">)</span><span class="sc">;</span> <span class="c"># entire file in scalar</span></li><li> <span class="i">@all_lines</span> = <span class="i">read_file</span><span class="s">(</span><span class="i">$filename</span><span class="s">)</span><span class="sc">;</span> <span class="c"># one line per element</span></li></ol></pre><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="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a> <span class="s">(</span><span class="w">INPUT</span><span class="cm">,</span> <span class="i">$file</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't open $file: $!"</span><span class="sc">;</span></li><li> while <span class="s">(</span><span class="q"><INPUT></span><span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/chomp.html">chomp</a><span class="sc">;</span></li><li> <span class="c"># do something with $_</span></li><li> <span class="s">}</span></li><li> <a class="l_k" href="functions/close.html">close</a><span class="s">(</span><span class="w">INPUT</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't close $file: $!"</span><span class="sc">;</span></li></ol></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="verbatim"><ol><li> <span class="i">@lines</span> = <span class="q"><INPUT></span><span class="sc">;</span></li></ol></pre><p>you should think long and hard about why you need everything loaded at
once. It's just not a scalable solution. You might also find it more
fun to use the standard Tie::File module, or the DB_File module's
$DB_RECNO bindings, which allow you to tie an array to a file so that
accessing an element the array actually accesses the corresponding
line in the file.</p>
<p>You can read the entire filehandle contents into a scalar.</p>
<pre class="verbatim"><ol><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/local.html">local</a><span class="s">(</span><span class="i">*INPUT</span><span class="cm">,</span> <span class="i">$/</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a> <span class="s">(</span><span class="w">INPUT</span><span class="cm">,</span> <span class="i">$file</span><span class="s">)</span> || <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't open $file: $!"</span><span class="sc">;</span></li><li> <span class="i">$var</span> = <span class="q"><INPUT></span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></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="verbatim"><ol><li> <span class="i">$var</span> = <a class="l_k" href="functions/do.html">do</a> <span class="s">{</span> <a class="l_k" href="functions/local.html">local</a> <span class="i">$/</span><span class="sc">;</span> <span class="q"><INPUT></span> <span class="s">}</span><span class="sc">;</span></li></ol></pre><p>For ordinary files you can also use the read function.</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/read.html">read</a><span class="s">(</span> <span class="w">INPUT</span><span class="cm">,</span> <span class="i">$var</span><span class="cm">,</span> -s <span class="w">INPUT</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The third argument tests the byte size of the data on the INPUT filehandle
and reads that many bytes into the buffer $var.</p>
<a name="How-can-I-read-in-a-file-by-paragraphs%3f"></a><h2>How can I read in a file by paragraphs?
</h2>
<p>Use the <code class="inline"><span class="i">$/</span></code>
variable (see <a href="perlvar.html">perlvar</a> for details). You can either
set it to <code class="inline"><span class="q">""</span></code>
to eliminate empty paragraphs (<code class="inline"><span class="q">"abc\n\n\n\ndef"</span></code>
,
for instance, gets treated as two paragraphs and not three), or
<code class="inline"><span class="q">"\n\n"</span></code>
to accept empty paragraphs.</p>
<p>Note that a blank line must have no blanks in it. Thus
<code class="inline"><span class="q">"fred\n \nstuff\n\n"</span></code>
is one paragraph, but <code class="inline"><span class="q">"fred\n\nstuff\n\n"</span></code>
is two.</p>
<a name="How-can-I-read-a-single-character-from-a-file%3f--From-the-keyboard%3f"></a><h2>How can I read a single character from a file? From the keyboard?
</h2>
<p>You can use the builtin <code class="inline"><a class="l_k" href="functions/getc.html">getc()</a></code> function for most filehandles, but
it won'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="functions/getc.html">getc</a>.</p>
<p>If your system supports the portable operating system programming
interface (POSIX), you can use the following code, which you'll note
turns off echo processing as well.</p>
<pre class="verbatim"><ol><li> <span class="c">#!/usr/bin/perl -w</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">strict</span><span class="sc">;</span></li><li> <span class="i">$|</span> = <span class="n">1</span><span class="sc">;</span></li><li> for <span class="s">(</span><span class="n">1</span>..<span class="n">4</span><span class="s">)</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$got</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"gimme: "</span><span class="sc">;</span></li><li> <span class="i">$got</span> = <span class="i">getone</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"--> $got\n"</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li> <a class="l_k" href="functions/exit.html">exit</a><span class="sc">;</span></li><li></li><li> BEGIN <span class="s">{</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="q">qw(:termios_h)</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="s">(</span><span class="i">$term</span><span class="cm">,</span> <span class="i">$oterm</span><span class="cm">,</span> <span class="i">$echo</span><span class="cm">,</span> <span class="i">$noecho</span><span class="cm">,</span> <span class="i">$fd_stdin</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <span class="i">$fd_stdin</span> = <a class="l_k" href="functions/fileno.html">fileno</a><span class="s">(</span><span class="w">STDIN</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <span class="i">$term</span> = <span class="w">POSIX::Termios</span><span class="w">->new</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$term</span><span class="i">->getattr</span><span class="s">(</span><span class="i">$fd_stdin</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$oterm</span> = <span class="i">$term</span><span class="i">->getlflag</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <span class="i">$echo</span> = <span class="w">ECHO</span> | <span class="w">ECHOK</span> | <span class="w">ICANON</span><span class="sc">;</span></li><li> <span class="i">$noecho</span> = <span class="i">$oterm</span> & ~<span class="i">$echo</span><span class="sc">;</span></li><li></li><li><a name="cbreak"></a> sub <span class="m">cbreak</span> <span class="s">{</span></li><li> <span class="i">$term</span><span class="i">->setlflag</span><span class="s">(</span><span class="i">$noecho</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$term</span><span class="i">->setcc</span><span class="s">(</span><span class="w">VTIME</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$term</span><span class="i">->setattr</span><span class="s">(</span><span class="i">$fd_stdin</span><span class="cm">,</span> <span class="w">TCSANOW</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li><a name="cooked"></a> sub <span class="m">cooked</span> <span class="s">{</span></li><li> <span class="i">$term</span><span class="i">->setlflag</span><span class="s">(</span><span class="i">$oterm</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$term</span><span class="i">->setcc</span><span class="s">(</span><span class="w">VTIME</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">$term</span><span class="i">->setattr</span><span class="s">(</span><span class="i">$fd_stdin</span><span class="cm">,</span> <span class="w">TCSANOW</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li><a name="getone"></a> sub <span class="m">getone</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$key</span> = <span class="q">''</span><span class="sc">;</span></li><li> <span class="i">cbreak</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/sysread.html">sysread</a><span class="s">(</span><span class="w">STDIN</span><span class="cm">,</span> <span class="i">$key</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="i">cooked</span><span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/return.html">return</a> <span class="i">$key</span><span class="sc">;</span></li><li> <span class="s">}</span></li><li></li><li> <span class="s">}</span></li><li></li><li> END <span class="s">{</span> <span class="i">cooked</span><span class="s">(</span><span class="s">)</span> <span class="s">}</span></li></ol></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="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">Term::ReadKey</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">TTY</span><span class="cm">,</span> <span class="q">"</dev/tty"</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"Gimme a char: "</span><span class="sc">;</span></li><li> <span class="w">ReadMode</span> <span class="q">"raw"</span><span class="sc">;</span></li><li> <span class="i">$key</span> = <span class="w">ReadKey</span> <span class="n">0</span><span class="cm">,</span> <span class="i">*TTY</span><span class="sc">;</span></li><li> <span class="w">ReadMode</span> <span class="q">"normal"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/printf.html">printf</a> <span class="q">"\nYou said %s, char number %03d\n"</span><span class="cm">,</span></li><li> <span class="i">$key</span><span class="cm">,</span> <a class="l_k" href="functions/ord.html">ord</a> <span class="i">$key</span><span class="sc">;</span></li></ol></pre><a name="How-can-I-tell-whether-there's-a-character-waiting-on-a-filehandle%3f"></a><h2>How can I tell whether there'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's very system dependent. Here's one solution that works on BSD
systems:</p>
<pre class="verbatim"><ol><li><a name="key_ready"></a> sub <span class="m">key_ready</span> <span class="s">{</span></li><li> <a class="l_k" href="functions/my.html">my</a><span class="s">(</span><span class="i">$rin</span><span class="cm">,</span> <span class="i">$nfd</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/vec.html">vec</a><span class="s">(</span><span class="i">$rin</span><span class="cm">,</span> <a class="l_k" href="functions/fileno.html">fileno</a><span class="s">(</span><span class="w">STDIN</span><span class="s">)</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span> = <span class="n">1</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/return.html">return</a> <span class="i">$nfd</span> = <a class="l_k" href="functions/select.html">select</a><span class="s">(</span><span class="i">$rin</span><span class="cm">,</span><a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span><a class="l_k" href="functions/undef.html">undef</a><span class="cm">,</span><span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><p>If you want to find out how many characters are waiting, there'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 class="inline"><a class="l_k" href="functions/require.html">require</a></code>d. FIONREAD ends up defined as a function in the
<i>sys/ioctl.ph</i> file:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/require.html">require</a> <span class="q">'sys/ioctl.ph'</span><span class="sc">;</span></li><li></li><li> <span class="i">$size</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">"L"</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/ioctl.html">ioctl</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">FIONREAD</span><span class="s">(</span><span class="s">)</span><span class="cm">,</span> <span class="i">$size</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Couldn't call ioctl: $!\n"</span><span class="sc">;</span></li><li> <span class="i">$size</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">"L"</span><span class="cm">,</span> <span class="i">$size</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>If <i>h2ph</i> wasn't installed or doesn't work for you, you can
<i>grep</i> the include files by hand:</p>
<pre class="verbatim"><ol><li> % grep FIONREAD /usr/include/*/*</li><li> /usr/include/asm/ioctls.h:#define FIONREAD 0x541B</li></ol></pre><p>Or write a small C program using the editor of champions:</p>
<pre class="verbatim"><ol><li> % cat > fionread.c</li><li> #include <sys/ioctl.h></li><li> main() {</li><li> printf("%#08x\n", FIONREAD);</li><li> }</li><li> ^D</li><li> % cc -o fionread fionread.c</li><li> % ./fionread</li><li> 0x4004667f</li></ol></pre><p>And then hard code it, leaving porting as an exercise to your successor.</p>
<pre class="verbatim"><ol><li> <span class="i">$FIONREAD</span> = <span class="n">0x4004667f</span><span class="sc">;</span> <span class="c"># XXX: opsys dependent</span></li><li></li><li> <span class="i">$size</span> = <a class="l_k" href="functions/pack.html">pack</a><span class="s">(</span><span class="q">"L"</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/ioctl.html">ioctl</a><span class="s">(</span><span class="w">FH</span><span class="cm">,</span> <span class="i">$FIONREAD</span><span class="cm">,</span> <span class="i">$size</span><span class="s">)</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Couldn't call ioctl: $!\n"</span><span class="sc">;</span></li><li> <span class="i">$size</span> = <a class="l_k" href="functions/unpack.html">unpack</a><span class="s">(</span><span class="q">"L"</span><span class="cm">,</span> <span class="i">$size</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>FIONREAD requires a filehandle connected to a stream, meaning that sockets,
pipes, and tty devices work, but <i>not</i> files.</p>
<a name="How-do-I-do-a-tail--f-in-perl%3f"></a><h2>How do I do a <code class="inline"><span class="w">tail</span> -f</code>
in perl?
</h2>
<p>First try</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/seek.html">seek</a><span class="s">(</span><span class="w">GWFILE</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The statement <code class="inline"><a class="l_k" href="functions/seek.html">seek</a><span class="s">(</span><span class="w">GWFILE</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">1</span><span class="s">)</span></code>
doesn't change the current position,
but it does clear the end-of-file condition on the handle, so that the
next <code class="inline"><span class="q"><GWFILE></span></code>
makes Perl try again to read something.</p>
<p>If that doesn't work (it relies on features of your stdio implementation),
then you need something more like this:</p>
<pre class="verbatim"><ol><li> for <span class="s">(</span><span class="sc">;</span><span class="sc">;</span><span class="s">)</span> <span class="s">{</span></li><li> for <span class="s">(</span><span class="i">$curpos</span> = <a class="l_k" href="functions/tell.html">tell</a><span class="s">(</span><span class="w">GWFILE</span><span class="s">)</span><span class="sc">;</span> <span class="q"><GWFILE></span><span class="sc">;</span> <span class="i">$curpos</span> = <a class="l_k" href="functions/tell.html">tell</a><span class="s">(</span><span class="w">GWFILE</span><span class="s">)</span><span class="s">)</span> <span class="s">{</span></li><li> <span class="c"># search for some stuff and put it into files</span></li><li> <span class="s">}</span></li><li> <span class="c"># sleep for a while</span></li><li> <a class="l_k" href="functions/seek.html">seek</a><span class="s">(</span><span class="w">GWFILE</span><span class="cm">,</span> <span class="i">$curpos</span><span class="cm">,</span> <span class="n">0</span><span class="s">)</span><span class="sc">;</span> <span class="c"># seek to where we had been</span></li><li> <span class="s">}</span></li></ol></pre><p>If this still doesn't work, look into the <code class="inline"><span class="w">clearerr</span></code>
method
from <code class="inline"><span class="w">IO::Handle</span></code>
, which resets the error and end-of-file states
on the handle.</p>
<p>There's also a <code class="inline"><span class="w">File::Tail</span></code>
module from CPAN.</p>
<a name="How-do-I-dup()-a-filehandle-in-Perl%3f"></a><h2>How do I dup() a filehandle in Perl?
</h2>
<p>If you check <a href="functions/open.html">open</a>, you'll see that several of the ways
to call open() should do the trick. For example:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">LOG</span><span class="cm">,</span> <span class="q">">>/foo/logfile"</span><span class="s">)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">STDERR</span><span class="cm">,</span> <span class="q">">&LOG"</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Or even with a literal numeric descriptor:</p>
<pre class="verbatim"><ol><li> <span class="i">$fd</span> = <span class="i">$ENV</span>{<span class="w">MHCONTEXTFD</span>}<span class="sc">;</span></li><li> <a class="l_k" href="functions/open.html">open</a><span class="s">(</span><span class="w">MHCONTEXT</span><span class="cm">,</span> <span class="q">"<&=$fd"</span><span class="s">)</span><span class="sc">;</span> <span class="c"># like fdopen(3S)</span></li></ol></pre><p>Note that "<&STDIN" makes a copy, but "<&=STDIN" make
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>
<a name="How-do-I-close-a-file-descriptor-by-number%3f"></a><h2>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 class="inline"><span class="w">POSIX::open</span></code>
), you can use the
<code class="inline"><a class="l_k" href="functions/close.html">close()</a></code> function from the <code class="inline"><span class="w">POSIX</span></code>
module:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">POSIX</span> <span class="s">(</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <span class="i">POSIX::close</span><span class="s">(</span> <span class="i">$fd</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>This should rarely be necessary, as the Perl <code class="inline"><a class="l_k" href="functions/close.html">close()</a></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 class="inline"><span class="w">MHCONTEXT</span></code>
above. But if you really have
to, you may be able to do this:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/require.html">require</a> <span class="q">'sys/syscall.ph'</span><span class="sc">;</span></li><li> <span class="i">$rc</span> = <a class="l_k" href="functions/syscall.html">syscall</a><span class="s">(</span><span class="i">&SYS_close</span><span class="cm">,</span> <span class="i">$fd</span> + <span class="n">0</span><span class="s">)</span><span class="sc">;</span> <span class="c"># must force numeric</span></li><li> <a class="l_k" href="functions/die.html">die</a> <span class="q">"can't sysclose $fd: $!"</span> unless <span class="i">$rc</span> == <span class="n">-1</span><span class="sc">;</span></li></ol></pre><p>Or, just use the fdopen(3S) feature of <code class="inline"><a class="l_k" href="functions/open.html">open()</a></code>:</p>
<pre class="verbatim"><ol><li> <span class="s">{</span></li><li> <a class="l_k" href="functions/open.html">open</a> <a class="l_k" href="functions/my.html">my</a><span class="s">(</span> <span class="i">$fh</span> <span class="s">)</span><span class="cm">,</span> <span class="q">"<&=$fd"</span> or <a class="l_k" href="functions/die.html">die</a> <span class="q">"Cannot reopen fd=$fd: $!"</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/close.html">close</a> <span class="i">$fh</span><span class="sc">;</span></li><li> <span class="s">}</span></li></ol></pre><a name="Why-can't-I-use-%22C%3a%5ctemp%5cfoo%22-in-DOS-paths%3f--Why-doesn't-%60C%3a%5ctemp%5cfoo.exe%60-work%3f"></a><h2>Why can't I use "C:\temp\foo" in DOS paths? Why doesn'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 ("like\this"), the
backslash is an escape character. The full list of these is in
<a href="perlop.html#Quote-and-Quote-like-Operators">"Quote and Quote-like Operators" in perlop</a>. Unsurprisingly, you don't
have a file called "c:(tab)emp(formfeed)oo" or
"c:(tab)emp(formfeed)oo.exe" 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 class="inline">/</code> and <code class="inline">\</code>
the same in a path, you might as well use the
one that doesn'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>
<a name="Why-doesn't-glob(%22*.*%22)-get-all-the-files%3f"></a><h2>Why doesn't glob("*.*") get all the files?
</h2>
<p>Because even on non-Unix ports, Perl's glob function follows standard
Unix globbing semantics. You'll need <code class="inline"><a class="l_k" href="functions/glob.html">glob("*")</a></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>
<a name="Why-does-Perl-let-me-delete-read-only-files%3f--Why-does--i-clobber-protected-files%3f--Isn't-this-a-bug-in-Perl%3f"></a><h2>Why does Perl let me delete read-only files? Why does <code class="inline">-<span class="w">i</span></code>
clobber protected files? Isn't this a bug in Perl?</h2>
<p>This is elaborately and painstakingly described in the
<i>file-dir-perms</i> article in the "Far More Than You Ever Wanted To
Know" 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'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're allowed to.</p>
<a name="How-do-I-select-a-random-line-from-a-file%3f"></a><h2>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's a reservoir-sampling algorithm from the Camel Book:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/srand.html">srand</a><span class="sc">;</span></li><li> <a class="l_k" href="functions/rand.html">rand</a><span class="s">(</span><span class="i">$.</span><span class="s">)</span> < <span class="n">1</span> && <span class="s">(</span><span class="i">$line</span> = <span class="i">$_</span><span class="s">)</span> while <><span class="sc">;</span></li></ol></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 <code class="inline"><span class="w">File::Random</span></code>
module which provides a function
for that algorithm:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Random</span> <span class="q">qw/random_line/</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$line</span> = <span class="i">random_line</span><span class="s">(</span><span class="i">$filename</span><span class="s">)</span><span class="sc">;</span></li></ol></pre><p>Another way is to use the <code class="inline"><span class="w">Tie::File</span></code>
module, which treats the entire
file as an array. Simply access a random array element.</p>
<a name="Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines%3f"></a><h2>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="verbatim"><ol><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">@animals</span> = <span class="q">qw(camel llama alpaca vicuna)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"animals are: @animals\n"</span><span class="sc">;</span></li></ol></pre><p>It's the double quotes, not the <code class="inline"><a class="l_k" href="functions/print.html">print</a></code>, doing this. Whenever you
interpolate an array in a double quote context, Perl joins the
elements with spaces (or whatever is in <code class="inline"><span class="i">$"</span></code>
, which is a space by
default):</p>
<pre class="verbatim"><ol><li> animals are: camel llama alpaca vicuna</li></ol></pre><p>This is different than printing the array without the interpolation:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">@animals</span> = <span class="q">qw(camel llama alpaca vicuna)</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/print.html">print</a> <span class="q">"animals are: "</span><span class="cm">,</span> <span class="i">@animals</span><span class="cm">,</span> <span class="q">"\n"</span><span class="sc">;</span></li></ol></pre><p>Now the output doesn't have the spaces between the elements because
the elements of <code class="inline"><span class="i">@animals</span></code>
simply become part of the list to
<code class="inline"><a class="l_k" href="functions/print.html">print</a></code>:</p>
<pre class="verbatim"><ol><li> animals are: camelllamaalpacavicuna</li></ol></pre><p>You might notice this when each of the elements of <code class="inline"><span class="i">@array</span></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="verbatim"><ol><li> <span class="w">this</span> <span class="w">is</span> <span class="w">a</span> <span class="w">line</span></li><li> <span class="w">this</span> <span class="w">is</span> <span class="w">another</span> <span class="w">line</span></li><li> <span class="w">this</span> <span class="w">is</span> <span class="w">the</span> <span class="w">third</span> <span class="w">line</span></li></ol></pre><p>That extra space comes from the interpolation of the array. If you
don't want to put anything between your array elements, don't use the
array in double quotes. You can send it to print without them:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/print.html">print</a> <span class="i">@lines</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-traverse-a-directory-tree%3f"></a><h2>How do I traverse a directory tree?</h2>
<p>(contributed by brian d foy)</p>
<p>The <code class="inline"><span class="w">File::Find</span></code>
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 class="inline"><span class="w">find</span></code>
subroutine with a callback subroutine and the
directories you want to traverse:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Find</span><span class="sc">;</span></li><li></li><li> <span class="i">find</span><span class="s">(</span> \<span class="i">&wanted</span><span class="cm">,</span> <span class="i">@directories</span> <span class="s">)</span><span class="sc">;</span></li><li></li><li><a name="wanted"></a> sub <span class="m">wanted</span> <span class="s">{</span></li><li> <span class="c"># full path in $File::Find::name</span></li><li> <span class="c"># just filename in $_</span></li><li> ... <a class="l_k" href="functions/do.html">do</a> <span class="w">whatever</span> <span class="w">you</span> <span class="w">want</span> <span class="w">to</span> <a class="l_k" href="functions/do.html">do</a> ...</li><li> <span class="s">}</span></li></ol></pre><p>The <code class="inline"><span class="w">File::Find::Closures</span></code>
, which you can download from CPAN, provides
many ready-to-use subroutines that you can use with <code class="inline"><span class="w">File::Find</span></code>
.</p>
<p>The <code class="inline"><span class="w">File::Finder</span></code>
, which you can download from CPAN, can help you
create the callback subroutine using something closer to the syntax of
the <code class="inline"><span class="w">find</span></code>
command-line utility:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Find</span><span class="sc">;</span></li><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Finder</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">$deep_dirs</span> = <span class="w">File::Finder</span><span class="w">->depth</span><span class="w">->type</span><span class="s">(</span><span class="q">'d'</span><span class="s">)</span><span class="i">->ls</span><span class="i">->exec</span><span class="s">(</span><span class="q">'rmdir'</span><span class="cm">,</span><span class="q">'{}'</span><span class="s">)</span><span class="sc">;</span></li><li></li><li> <span class="i">find</span><span class="s">(</span> <span class="i">$deep_dirs</span><span class="i">->as_options</span><span class="cm">,</span> <span class="i">@places</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The <code class="inline"><span class="w">File::Find::Rule</span></code>
module, which you can download from CPAN, has
a similar interface, but does the traversal for you too:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Find::Rule</span><span class="sc">;</span></li><li></li><li> <a class="l_k" href="functions/my.html">my</a> <span class="i">@files</span> = <span class="w">File::Find::Rule</span><span class="w">->file</span><span class="s">(</span><span class="s">)</span></li><li> <span class="i">->name</span><span class="s">(</span> <span class="q">'*.pm'</span> <span class="s">)</span></li><li> <span class="i">->in</span><span class="s">(</span> <span class="i">@INC</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><a name="How-do-I-delete-a-directory-tree%3f"></a><h2>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's built-in <code class="inline"><a class="l_k" href="functions/rmdir.html">rmdir</a></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 <code class="inline"><span class="w">File::Path</span></code>
module, which comes with Perl, has a <code class="inline"><span class="w">rmtree</span></code>
which
can take care of all of the hard work for you:</p>
<pre class="verbatim"><ol><li> <a class="l_k" href="functions/use.html">use</a> <span class="w">File::Path</span> <span class="q">qw(rmtree)</span><span class="sc">;</span></li><li></li><li> <span class="i">rmtree</span><span class="s">(</span> \<span class="i">@directories</span><span class="cm">,</span> <span class="n">0</span><span class="cm">,</span> <span class="n">0</span> <span class="s">)</span><span class="sc">;</span></li></ol></pre><p>The first argument to <code class="inline"><span class="w">rmtree</span></code>
is either a string representing a directory path
or an array reference. The second argument controls progress messages, and the
third argument controls the handling of files you don't have permissions to
delete. See the <code class="inline"><span class="w">File::Path</span></code>
module for the details.</p>
<a name="How-do-I-copy-an-entire-directory%3f"></a><h2>How do I copy an entire directory?</h2>
<p>(contributed by Shlomi Fish)</p>
<p>To do the equivalent of <code class="inline"><span class="w">cp</span> -R</code>
(i.e. copy an entire directory tree
recursively) in portable Perl, you'll either need to write something yourself
or find a good CPAN module such as <a href="http://search.cpan.org/perldoc/File::Copy::Recursive">File::Copy::Recursive</a>.
=head1 REVISION</p>
<p>Revision: $Revision$</p>
<p>Date: $Date$</p>
<p>See <a href="perlfaq.html">perlfaq</a> for source control details and availability.</p>
<a name="AUTHOR-AND-COPYRIGHT"></a><h1>AUTHOR AND COPYRIGHT</h1>
<p>Copyright (c) 1997-2009 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>
<div id="page_index">
<div id="page_index_header">
<div id="page_index_close"><a href="#" onClick="pageIndex.hide();return false;"></a></div>
<div id="page_index_title"><span class="page_index_top">Page index</span></div>
<div id="page_index_topright"></div>
</div>
<div id="page_index_content">
<ul><li><a href="#NAME">NAME</a><li><a href="#DESCRIPTION">DESCRIPTION</a><ul><li><a href="#How-do-I-flush%2funbuffer-an-output-filehandle%3f--Why-must-I-do-this%3f">How do I flush/unbuffer an output filehandle? Why must I do this?
</a><li><a href="#How-do-I-change%2c-delete%2c-or-insert-a-line-in-a-file%2c-or-append-to-the-beginning-of-a-file%3f">How do I change, delete, or insert a line in a file, or append to the beginning of a file?
</a><li><a href="#How-do-I-count-the-number-of-lines-in-a-file%3f">How do I count the number of lines in a file?
</a><li><a href="#How-can-I-use-Perl's--i-option-from-within-a-program%3f">How can I use Perl's -i option from within a program?
</a><li><a href="#How-can-I-copy-a-file%3f">How can I copy a file?
</a><li><a href="#How-do-I-make-a-temporary-file-name%3f">How do I make a temporary file name?
</a><li><a href="#How-can-I-manipulate-fixed-record-length-files%3f">How can I manipulate fixed-record-length files?
</a><li><a href="#How-can-I-make-a-filehandle-local-to-a-subroutine%3f--How-do-I-pass-filehandles-between-subroutines%3f--How-do-I-make-an-array-of-filehandles%3f">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><a href="#How-can-I-use-a-filehandle-indirectly%3f">How can I use a filehandle indirectly?
</a><li><a href="#How-can-I-set-up-a-footer-format-to-be-used-with-write()%3f">How can I set up a footer format to be used with write()?
</a><li><a href="#How-can-I-write()-into-a-string%3f">How can I write() into a string?
</a><li><a href="#How-can-I-open-a-filehandle-to-a-string%3f">How can I open a filehandle to a string?
</a><li><a href="#How-can-I-output-my-numbers-with-commas-added%3f">How can I output my numbers with commas added?
</a><li><a href="#How-can-I-translate-tildes-(~)-in-a-filename%3f">How can I translate tildes (~) in a filename?
</a><li><a href="#How-come-when-I-open-a-file-read-write-it-wipes-it-out%3f">How come when I open a file read-write it wipes it out?
</a><li><a href="#Why-do-I-sometimes-get-an-%22Argument-list-too-long%22-when-I-use-%3c*%3e%3f">Why do I sometimes get an "Argument list too long" when I use <*>?
</a><li><a href="#Is-there-a-leak%2fbug-in-glob()%3f">Is there a leak/bug in glob()?
</a><li><a href="#How-can-I-open-a-file-with-a-leading-%22%3e%22-or-trailing-blanks%3f">How can I open a file with a leading ">" or trailing blanks?
</a><li><a href="#How-can-I-reliably-rename-a-file%3f">How can I reliably rename a file?
</a><li><a href="#How-can-I-lock-a-file%3f">How can I lock a file?
</a><li><a href="#Why-can't-I-just-open(FH%2c-%22%3efile.lock%22)%3f">Why can't I just open(FH, ">file.lock")?
</a><li><a href="#I-still-don't-get-locking.--I-just-want-to-increment-the-number-in-the-file.--How-can-I-do-this%3f">I still don't get locking. I just want to increment the number in the file. How can I do this?
</a><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%3f">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><a href="#How-do-I-randomly-update-a-binary-file%3f">How do I randomly update a binary file?
</a><li><a href="#How-do-I-get-a-file's-timestamp-in-perl%3f">How do I get a file's timestamp in perl?
</a><li><a href="#How-do-I-set-a-file's-timestamp-in-perl%3f">How do I set a file's timestamp in perl?
</a><li><a href="#How-do-I-print-to-more-than-one-file-at-once%3f">How do I print to more than one file at once?
</a><li><a href="#How-can-I-read-in-an-entire-file-all-at-once%3f">How can I read in an entire file all at once?
</a><li><a href="#How-can-I-read-in-a-file-by-paragraphs%3f">How can I read in a file by paragraphs?
</a><li><a href="#How-can-I-read-a-single-character-from-a-file%3f--From-the-keyboard%3f">How can I read a single character from a file? From the keyboard?
</a><li><a href="#How-can-I-tell-whether-there's-a-character-waiting-on-a-filehandle%3f">How can I tell whether there's a character waiting on a filehandle?</a><li><a href="#How-do-I-do-a-tail--f-in-perl%3f">How do I do a tail -f in perl?
</a><li><a href="#How-do-I-dup()-a-filehandle-in-Perl%3f">How do I dup() a filehandle in Perl?
</a><li><a href="#How-do-I-close-a-file-descriptor-by-number%3f">How do I close a file descriptor by number?
</a><li><a href="#Why-can't-I-use-%22C%3a%5ctemp%5cfoo%22-in-DOS-paths%3f--Why-doesn't-%60C%3a%5ctemp%5cfoo.exe%60-work%3f">Why can't I use "C:\temp\foo" in DOS paths? Why doesn't `C:\temp\foo.exe` work?
</a><li><a href="#Why-doesn't-glob(%22*.*%22)-get-all-the-files%3f">Why doesn't glob("*.*") get all the files?
</a><li><a href="#Why-does-Perl-let-me-delete-read-only-files%3f--Why-does--i-clobber-protected-files%3f--Isn't-this-a-bug-in-Perl%3f">Why does Perl let me delete read-only files? Why does -i clobber protected files? Isn't this a bug in Perl?</a><li><a href="#How-do-I-select-a-random-line-from-a-file%3f">How do I select a random line from a file?
</a><li><a href="#Why-do-I-get-weird-spaces-when-I-print-an-array-of-lines%3f">Why do I get weird spaces when I print an array of lines?</a><li><a href="#How-do-I-traverse-a-directory-tree%3f">How do I traverse a directory tree?</a><li><a href="#How-do-I-delete-a-directory-tree%3f">How do I delete a directory tree?</a><li><a href="#How-do-I-copy-an-entire-directory%3f">How do I copy an entire directory?</a></ul><li><a href="#AUTHOR-AND-COPYRIGHT">AUTHOR AND COPYRIGHT</a></ul>
</div>
<div id="page_index_footer">
<div id="page_index_bottomleft"></div>
<div id="page_index_bottom"><span class="page_index_bottom"></span></div>
<div id="page_index_resize"></div>
</div>
</div>
</div>
<div id="content_footer">
</div>
</div>
<div id="right_column">
<div class="side_group">
<div class="side_panel tools_panel">
<p>Recently read</p>
<div id="recent_pages"></div>
</div>
<div class="side_panel tools_panel">
<p>Tools</p>
<ul>
<li><a href="preferences.html">Preferences</a>
</ul>
</div>
</div>
</div>
<div class="clear"></div>
</div>
<div id="footer">
<div id="footer_content">
</div>
</div>
</div>
<script language="JavaScript" src="static/combined-20090809.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
perldoc.setPath(0);
perldoc.pageName = 'perlfaq5';
perldoc.pageAddress = 'perlfaq5.html';
perldoc.contentPage = 1;
</script>
</body>
</html>
|