Directory Access
- Here's one way to do it:
print "Where to? "; chomp($newdir = <STDIN>); chdir($newdir) || die "Cannot chdir to $newdir: $!"; foreach (<*>) { print "$_\n"; }
The first two lines prompt for and read the name of the directory.
The third line attempts to change the directory to the given name, aborting if this isn't possible.
The
foreachloop steps through a list. But what's the list? It's the glob in a list context, which expands to a list of all of the filenames that match the pattern (here,*). - Here's one way to do it, with a directory handle:
print "Where to? "; chomp($newdir = <STDIN>); chdir($newdir) || die "Cannot chdir to $newdir: $!"; opendir(DOT,".") || die "Cannot opendir . (serious dainbramage): $!"; foreach (sort readdir(DOT)) { print "$_\n"; } closedir(DOT);
Just as with the previous program, we prompt and read a new directory. After we've
chdir'ed there, we open the directory creating a directory handle namedDOT. In theforeachloop, the list returned byreaddir(in a list context) is sorted, then stepped through, assigning each element to$_in turn.And here's how to do it with a glob instead:
print "Where to? "; chomp($newdir = <STDIN>); chdir($newdir) || die "Cannot chdir to $newdir: $!"; foreach (sort <* .*>) { print "$_\n"; }
Yes, this solution is basically the other program from the previous exercise, but I've added a
sortoperator in front of the glob, and I also added*to the glob to pick up the files that begin with dot. We need thesortbecause a file named!fredbelongs before the dot files, andbarneybelongs after them. In addition, an easy glob pattern that can get them all in the proper sequence does not exist.