O'Reilly logo

Learning Perl, 3rd Edition by Randal L. Schwartz, Tom Phoenix

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required