Working with Files with Perl

Advertisement

Advertisement

Overview

Introduction

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 a 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";

Conclusion

With this knowledge, you should be able to perform basic file manipulation tasks.

Advertisement

Advertisement