Chapter 13. Manipulating Files and Directories

Perl is commonly used to wrangle files and directories. Because Perl grew up in a Unix environment and still spends most of its time there, most of the description in this chapter may seem Unix-centric. But the nice thing is that to whatever degree possible, Perl works exactly the same way on non-Unix systems.

And now a word of warning—some cultures consider the number “13” to be very unlucky. We deliberately placed this material as Chapter 13 of this book, since we’re about to do some pretty dangerous things if bugs creep into the code (like remove files without a chance of recovery), so be very careful when you’re playing with the exercises.

Removing Files

Most of the time, we make files so that the data can stay around for a while. But when the data has outlived its life, it’s time to make the file go away. At the Unix shell level, we’d type an rm command to remove a file or files:

$ rm slate bedrock lava

In Perl, we use the unlink operator:

unlink "slate", "bedrock", "lava";

This sends the three named files away to bit heaven, never to be seen again.

Now, since unlink takes a list, and the glob function (described in Chapter 12) returns a list, we can combine the two to delete many files at once:

unlink glob "*.o";

This is similar to rm *.o at the shell, except that we didn’t have to fire off a separate rm process. So we can make those important files go away that much faster!

The return value from unlink tells us how many files ...

Get Learning Perl, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.