Always use the three-argument form of open to prevent injection attacks. Blocks auto-close handles cleanly.
| Name | Signature | Description |
|---|---|---|
| open | open(my $fh, MODE, $file) or die | Open file — use 3-arg form always |
| close | close($fh) | Close filehandle |
| <$fh> | readline($fh) or <$fh> | Read one line (or all lines in list context) |
| print $fh | print $fh $str | Write to filehandle |
| say $fh | say $fh $str | Write with newline to filehandle |
| eof | eof($fh) → bool | True if end of file |
| < | open MODE '<' — read | Open file for reading |
| > | open MODE '>' — write | Open file for writing (create/truncate) |
| >> | open MODE '>>' — append | Open file for appending |
| -e | file test | True if file exists |
| -f | file test | True if regular file |
| -d | file test | True if directory |
| -s | file test | File size in bytes |
| -r/-w/-x | file tests | Readable / writable / executable |
| unlink | unlink $file | Delete file |
| rename | rename $old, $new | Rename / move file |
| mkdir | mkdir $dir | Create directory |
| rmdir | rmdir $dir | Remove empty directory |
| opendir/readdir | opendir(my $dh, $dir); readdir($dh) | Read directory entries |
| glob | glob('*.pl') or <*.pl> | Filename globbing |
| File::Basename | use File::Basename; basename/dirname | Extract filename/directory from path |
| File::Find | use File::Find; find(\&wanted, @dirs) | Recursive directory traversal |
| File::Path | use File::Path 'make_path' | Create directory trees recursively |
| Cwd | use Cwd 'getcwd' | Get current working directory |
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