Answers to Chapter 13 Exercises
Here’s one way to do it, with a glob:
print "Which directory? (Default is your home directory) "; chomp(my $dir = <STDIN>); if ($dir =~ /^\s*$/) { # A blank line chdir or die "Can't chdir to your home directory: $!"; } else { chdir $dir or die "Can't chdir to '$dir': $!"; } my @files = <*>; foreach (@files) { print "$_\n"; }First, we show a simple prompt and read the desired directory, chomping it as needed. (Without a chomp, we’d be trying to head for a directory that ends in a newline—legal in Unix, and therefore cannot be presumed to simply be extraneous by the
chdirfunction.)Then, if the directory name is nonempty, we’ll change to that directory, aborting on a failure. If empty, the home directory is selected instead.
Finally, a glob on “star” pulls up all the names in the (new) working directory, automatically sorted in alphabetical order, and they’re printed one at a time.
Here’s one way to do it:
print "Which directory? (Default is your home directory) "; chomp(my $dir = <STDIN>); if ($dir =~ /^\s*$/) { # A blank line chdir or die "Can't chdir to your home directory: $!"; } else { chdir $dir or die "Can't chdir to '$dir': $!"; } my @files = <.* *>; ## now includes .* foreach (sort @files) { ## now sorts print "$_\n"; }Two differences from the previous one: first, the glob now includes “dot star”, which matches all the names that do begin with a dot. And second, we now must sort the resulting list because some of the names that begin with a dot ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access