Manipulate Files with Perl

Perl is commonly used for sysadmin tasks which frequently involves managing files. These examples demonstrate how to read, write, and append files with Perl.

Check if File Exists

if ( -e "test.txt") {
    print "File exists.";
}

Get File Size

my $fileSizeInBytes = -s 'test.txt';

Change File Permissions

chmod(0755, $filePath);

Deleting Files

unlink($filePath);

Opening and Closing Files

$file = '/home/NanoDano/test.txt';

# Pick only one of these
open(INFO, $file); # Open for input
open(INFO, "<$file"); # Another way for input
open(INFO, ">$file"); # Open for output
open(INFO, ">>$file"); # Open for appending

# Close when finished
close(INFO);

Read File Contents

# Store all the lines of the file in to an array
@lines = <INFO>;

Write to File

You can provide the print function a file handle to specify where to write the output. It defaults to standard output, but we can specify the file handler of our open file.

print INFO "This line goes to the file.\n";