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

Text Processing

  1. Unicode 🐪
  2. Convert File Encoding
  3. Read Write File
  4. Traverse Dir
  5. Find Replace
  6. Validate Local Links
  7. Split Line by Regex

Advanced

  1. Sort List, Matrix, Object
  2. Sort Matrix
  3. Sort Unstable
  4. Sort Misc
  5. List Modules, Search Paths
  6. Write a Module
  7. Complex Numbers
  8. System Call
  9. gzip
  10. Get Env Var
  11. GET Web Content
  12. Email