Languages: Python C C++ Go Java Ruby Rust Perl R ← Full TOC

← Perl Index

📁 File IO — File reading, writing, and directory operations

Always use the three-argument form of open to prevent injection attacks. Blocks auto-close handles cleanly.

📋 Functions & Syntax

NameSignatureDescription
openopen(my $fh, MODE, $file) or dieOpen file — use 3-arg form always
closeclose($fh)Close filehandle
<$fh>readline($fh) or <$fh>Read one line (or all lines in list context)
print $fhprint $fh $strWrite to filehandle
say $fhsay $fh $strWrite with newline to filehandle
eofeof($fh) → boolTrue if end of file
<open MODE '<' — readOpen file for reading
>open MODE '>' — writeOpen file for writing (create/truncate)
>>open MODE '>>' — appendOpen file for appending
-efile testTrue if file exists
-ffile testTrue if regular file
-dfile testTrue if directory
-sfile testFile size in bytes
-r/-w/-xfile testsReadable / writable / executable
unlinkunlink $fileDelete file
renamerename $old, $newRename / move file
mkdirmkdir $dirCreate directory
rmdirrmdir $dirRemove empty directory
opendir/readdiropendir(my $dh, $dir); readdir($dh)Read directory entries
globglob('*.pl') or <*.pl>Filename globbing
File::Basenameuse File::Basename; basename/dirnameExtract filename/directory from path
File::Finduse File::Find; find(\&wanted, @dirs)Recursive directory traversal
File::Pathuse File::Path 'make_path'Create directory trees recursively
Cwduse Cwd 'getcwd'Get current working directory

💡 Example

Run with perl script.pl.

#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use File::Basename;

# Write (3-arg open — always safe)
open(my $fh, '>', 'students.txt') or die "Cannot open: $!";
print $fh "$_\n" for ("Alice 95", "Bob 87", "Carol 92", "Dave 78");
close($fh);

# Read entire file at once (slurp)
open($fh, '<', 'students.txt') or die $!;
my @lines = <$fh>;
close($fh);
chomp @lines;
say "=== All students ===";
say for @lines;

# Process lines
say "=== Score >= 90 ===";
for (@lines) {
    my ($name, $score) = split;
    say "$name: $score" if defined $score && $score >= 90;
}

# Append
open($fh, '>>', 'students.txt') or die $!;
say $fh "Eve 98";
close($fh);

# File tests
printf "Exists: %s  Size: %d bytes  Readable: %s\n",
    (-e 'students.txt' ? 'yes':'no'),
    (-s 'students.txt'),
    (-r 'students.txt' ? 'yes':'no');

# basename/dirname
my $path = '/var/www/React/prod/toc1.html';
say "File: " . basename($path);
say "Dir : " . dirname($path);
say "Ext : " . (basename($path) =~ /\.(\w+)$/)[0];

# Read directory
opendir(my $dh, '.') or die $!;
my @txt = grep { /\.txt$/ && -f $_ } readdir($dh);
closedir($dh);
say "Text files: @txt";

unlink 'students.txt';
say "Done.";
# perl file_demo.pl

← Regex  |  🏠 Index  |  DBI →