O'Reilly logo

Learning Perl Student Workbook, 2nd Edition by brian d foy

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 can do the same thing with opendir, although you need to do a little more work:

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

opendir my( $dh ), '.' or die "Could not open directory! $!";
my @files = readdir( $dh );
closedir $dh;

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

print "I found $count files\n";

Answer 13.2: Use your program from the Answer to Exercise 13.1 to solve this one. In this case, you use next to skip any file that is a directory (some operating systems use regular files as directories). Since you have to acculumate a sum of file sizes, you might as well count the files at ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required