good chemistry is complicated, and a little bit messy -LW |
|
PerlMonks |
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.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;
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: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;
Now, you should get the output of just the Perl files within your directory.rewinddir(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.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;
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.1: use Cwd; 2: 3: print getcwd,"\n"; 4: chdir("C:\\"); 5: print getcwd;
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Navigating and Reading Directories
by sub_chick (Hermit) on Dec 12, 2005 at 05:28 UTC | |
Re: Navigating and Reading Directories (today)
by Anonymous Monk on Apr 23, 2015 at 11:06 UTC | |
Re: Navigating and Reading Directories
by salazar (Scribe) on Mar 05, 2009 at 17:33 UTC |