Perl
File I/O
Read and write files with filehandles.
By EZ4Code Team
fileio
Code
use strict;
use warnings;
# Write
open(my $fh, '>', 'output.txt') or die "Cannot open: $!";
print $fh "Line 1\n";
print $fh "Line 2\n";
close($fh);
# Read line by line
open(my $in, '<', 'input.txt') or die "Cannot open: $!";
while (my $line = <$in>) {
chomp $line; # remove newline
print "Read: $line\n";
}
close($in);
# Slurp entire file
open(my $slurp, '<', 'data.txt') or die $!;
my $content = do { local $/; <$slurp> };
close($slurp);
# Append
open(my $log, '>>', 'app.log') or die $!;
print $log "[" . localtime() . "] event\n";
close($log);
# Read all lines into array
open(my $arr, '<', 'data.txt') or die $!;
my @lines = <$arr>;
close($arr);
# In-place edit (perl -i -pe 's/old/new/g' file.txt)
{
local $^I = '.bak'; # backup extension
local @ARGV = ('data.txt');
while (<>) {
s/old/new/g;
print;
}
}Explanation
Always use the 3-arg open and check for errors (or die $!). Lexical filehandles (my $fh) auto-close on scope exit. local $/ temporarily disables the input record separator, slurping the whole file. chomp removes the trailing newline. The diamond operator <> reads from files in @ARGV or STDIN. $^I enables in-place editing (used by -i command-line flag).
More Perl Snippets
Scalars, Arrays, and Hashes
Perl's three main data types with sigils.
Regular Expressions
Perl is famous for its powerful regex support.
Subroutines and References
Define subs and use references for complex data.
Complex Data Structures
Build nested structures with references.
Modules and Packages
Create reusable modules with package keyword.
OOP with Moose
Modern object-oriented programming in Perl.