Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

II. Answers > M. Answers to Chapter 13 Exercises

Appendix M. Answers to Chapter 13 Exercises

Answer 13.1: You can use either a glob or opendir to get the number of files. In this case, you only want to report the number of files, so you can cheat a little. Use glob with two patterns at the same time: .* to find the hidden files and * that finds the rest. Store those in @files, and mixed in that list are the virtual files, . and .., that you don’t want to count. To get the total, subtract two from the number of elements in @files:

#!/usr/bin/perl
use strict;
use warnings;

my @files = glob( '.* *' );

# don't count . or ..
my $count = @files - 2;

print "I found $count files\n";

If you didn’t use that trick, you really don’t have that much more work to do:

#!/usr/bin/perl
use strict;
use warnings;

my @files = glob( '.* *' );

# don't count . or ..
foreach my $file ( @files ) {
    next if $file =~ /^\.{1,2}$/;
    $count++;
    }

print "I found $count files\n";

  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial