Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?

Navigating and Reading Directories

by Sherlock (Deacon)
on Apr 20, 2001 at 02:00 UTC ( #74013=perltutorial: print w/replies, xml ) Need Help??

This is a fairly straightforward tutorial of how to open a directory, read the contents from that directory, and change directories.

There are 7 basic functions that can be utilized to navigate through directories: opendir, readdir, closedir, rewinddir, telldir, seekdir, chdir. I'll give you an example of how to use each of these to help get you started.

opendir, readdir, & closedir

Let's start with the following code:
1 : use Cwd; 2 : 3 : my $dir = getcwd; 4 : 5 : opendir (DIR, $dir) or die $!; 6 : my @dir = readdir DIR; 7 : 8 : foreach my $item (@dir) { 9 : print "$item\n"; 10: } 11: 12: closedir DIR;
This bit of code simply opens the current working directory (CWD) and then displays the contents of it on the screen (much like the 'dir' command in DOS or 'ls' on UNIX). Let's look at the code a piece at a time.

This line simply gives us access to the getcwd command that will retrieve the current working directory.

This line stores the CWD into the scalar $dir.

Open the directory using opendir. The function opendir will return true if it was successful, otherwise, it will return false. If the directory can't be opened (i.e. the directory doesn't exist), the opendir function will return false and the script will terminate.

Use the readdir function to store the contents of the file into @dir.

LINES 8-10:
Print each directory element onto the screen, one per line.

LINE 12:
Finally, close the file using the closedir function.


Now that we've seen how to use opendir, readdir, and closedir, we can look at a couple of the other functions for dealing with directories. First, let's look at rewinddir.

This bit of code will fill two arrays, @dir and @perlFiles. The array @dir will be filled with all of the contents of the directory and we'll use grep to filter the contents of the directory and put only Perl files (.pl files) into the array @perlFiles. Finally, we'll print just Perl files (as if we typed "dir *.pl" in DOS).
1 : use Cwd; 2 : 3 : my $dir = getcwd; 4 : 5 : opendir (DIR, $dir) or die $!; 6 : my @dir = readdir DIR; 7 : my @perlFiles = grep /\.pl/, readdir DIR; 8 : 9 : foreach my $item (@perlFiles) { 10: print "$item\n"; 11: } 12: 13: closedir DIR;
From this bit of code, you won't get any output. The reason is that when using the readdir function, the seekpointer (the file/directory currently being pointed to) has moved all the way to the end of the directory. If it hadn't, we wouldn't have all of the contents of our directory in @dir. Unfortnately, this leaves @perlFiles empty. To fix this, we need to reset the seekpointer to the beginning of the directory by using rewinddir. Add this line between lines 6 and 7:
Now, you should get the output of just the Perl files within your directory.

telldir & seekdir

You can also set the seekpointer to any position within the directory (rather than just the beginning) by using telldir and seekdir. The telldir function returns the current seekpointer and the seekdir function will set the seekpointer to a value returned by the telldir function. If this sounds confusing, try this script:
1 : use Cwd; 2 : 3 : my $dir = getcwd; 4 : my $dirPointer; 5 : 6 : opendir (DIR, $dir) or die $!; 7 : $dirPointer = telldir (DIR); 8 : 9 : my @dir = readdir DIR; 10: 11: seekdir (DIR, $dirPointer); 12: 13: my @perlFiles = grep /\.pl/, readdir DIR; 14: 15: foreach my $item (@perlFiles) { 16: print "$item\n"; 17: } 18: 19: closedir DIR;
In this script, I'm storing the original seekpointer (that being at the beginning of the directory), using telldir, and then later using seekdir to move the seekpointer to that point. In this case, we've recreated rewinddir. If you execute this script, you should get the exact same output that we got for the previous one.


The final function for dealing with directories is chdir. This one is pretty simple, pass it an expression and chdir will change the current working directory to that (if possible).
1: use Cwd; 2: 3: print getcwd,"\n"; 4: chdir("C:\\"); 5: print getcwd;
This little script will display the CWD and then try to change that CWD to "C:\". You might want to do a check in case it can't find that directory, but this was just a quick example.

With that, you should be able to navigate through directories pretty easily. For more information, you can take a look at The Perl Documentation.

Good luck!

- Sherlock

Replies are listed 'Best First'.
Re: Navigating and Reading Directories
by sub_chick (Hermit) on Dec 12, 2005 at 05:28 UTC
    I really do appreciate this tutorial...well written and helped me alot as a beginner with perl. Thanks alot for this!

    "Es gibt mehr zu Leben als Bücher, kennen Sie. Aber nicht viel mehr " -(Der Smiths)
Re: Navigating and Reading Directories (today)
by Anonymous Monk on Apr 23, 2015 at 11:06 UTC

    In today, reading directories is easier with Path::Tiny

    #!/usr/bin/perl -- use strict; use warnings; use Path::Tiny qw/ path cwd /; my $dir = cwd(); my @files = path( $dir )->children; my @perlFiles = path( $dir )->children( qr/\.pl$/i ); for my $pl ( @perlFiles ){ print "$pl\n"; }
Re: Navigating and Reading Directories
by salazar (Scribe) on Mar 05, 2009 at 17:33 UTC
    In full agreement with sub_chick, this is an awesome tutorial for beginners and will help me out greatly.

    Great job, thanks :-) .

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: perltutorial [id://74013]
[marioroy]: LA ++ ok.
[marioroy]: I wrote a mp3info script to see the arguments received with print "@ARGV\n";
[marioroy]: And compared with running find on the command line.
[marioroy]: Bye all.
[Lady_Aleena]: marioroy, bye.

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (8)
As of 2017-04-23 21:34 GMT
Find Nodes?
    Voting Booth?
    I'm a fool:

    Results (432 votes). Check out past polls.