Приглашаем посетить
Русская библиотека (biblioteka-rus.ru)

Section A.14.  Answer to Chapter 15 Exercise

Previous
Table of Contents
Next

A.14. Answer to Chapter 15 Exercise

  1. Here's one way to do it.

        #!/usr/bin/perl
        use Module::CoreList;
        my %modules = %{ $Module::CoreList::version{5.006} };
        print join "\n", keys %modules;
    

    This answer uses a hash reference (which you'll have to read about in Alpaca, but we gave you the part to get around that. You don't have to know how it all works as long as you know it does work. You can get the job done and learn the details later.)

  2. There are a couple ways to approach this problem. For our solution, we used the Cwd (current working directory) module to find out where we were in the filesystem. We used a glob to get the list of all the files in the current directory; the names don't have the directory information, so we have to add that. You could have used opendir too, but glob is less typing. Our glob pattern includes .* to get the Unix hidden files, which don't match the * pattern.

    Once we have all the filenames, we go through them with foreach. For every name, we call File::Spec->catfile( ) just like what that module shows in its documentation. We save the result in $path, then print that to standard output:

        #!/usr/bin/perl
         
        use Cwd;        # Current Working Directory
        use File::Spec;
         
        my $cwd = getcwd;
        my @files = glob ".* *";
         
        foreach my $file ( @files )
        {
        my $path = File::Spec->catfile( $cwd, $file );
        print "$path\n";
        }
    

  3. This answer is much easier than the previous one, even though you had to write the last program to use this one. The work happens in the while loop. For every line of input, we call the basename function from File::Basename. We cribbed directly from the File::Basename documentation. We pass the line of input directly to basename and save the result in $name. Since we didn't chomp the line, $name still has the trailing newline, so we can simply print the name to get one filename per line:

        #!/usr/bin/perl
         
        use File::Basename;
         
        while( <STDIN> )
        {
        my $name = basename( $_ );
         
        print $name;
        }
    

    Previous
    Table of Contents
    Next