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 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 like the previous program, we prompt and read a new directory. Once 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, and 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, it's basically the other program from the previous exercise, but I've added a
sortoperator in front of the glob and 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, butbarneybelongs after them, and there isn't an easy shell glob that can get them all in the proper sequence.