Perl: Read/Write to File

By Xah Lee. Date: . Last updated: .

Here is a example of reading in a file and print it out:

# -*- coding: utf-8 -*-
# perl

open(f,"<x.pl") or die "error: $!";
while ($line = <f>) {print $line}
close(f) or die "error: $!";
print "am printing myself\n";

The f in the above code is called a “file handle”. It is sometimes capitalized (e.g. open(F,"<x.pl")), and can also be a string instead (e.g. open("f","<x.pl") ).

The < in "<x.pl" means read. To open a file for writing, use >.

The <f> reads in a line from the file handle “f”.

In the line close(f) or die "error: $!";, it essentially means if (not close) then abort with error message. The die is abort, the $! is a predefined variable that holds system errors.

Here is a complete example of reading in a file and writing it to another file.

# -*- coding: utf-8 -*-
# perl

open(f1,"</Users/john/t1.txt") or die "error opening file f1: $!";
open(f2,">/Users/john/t2.txt") or die "error opening file f2: $!";
while ($line = <f1>) {print f2 $line;}
close(f1) or die "error: $!";
close(f2) or die "error: $!";

If you have a question, put $5 at patreon and message me.

Perl

  1. Perl Overview
  2. Version String
  3. Help System

Detail

  1. Quoting String
  2. Format String
  3. String Operations
  4. True, False
  5. if then else
  6. Loop
  7. List / Array
  8. Loop Thru List
  9. Map f to List
  10. List Comprehension
  11. Hash Table
  12. Function Optional Param
  13. regex
  14. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. List Modules, Search Paths
  4. Write a Module
  5. Read / Write File
  6. Traverse Dir
  7. Find / Replace
  8. Complex Numbers
  9. System Call
  10. Compress / Decompress gzip
  11. Get Env Var
  12. GET Web Content
  13. Unicode 🐪
  14. Convert File Encoding
  15. Sort Unstable