Section A.1. Answers for Chapter 2


A.1. Answers for Chapter 2

A.1.1. Exercise 1

Here's one way to do it. The command-line arguments show up in the special array @ARGV, so we use that for our input list. The file test operator -s works on $_ by default, and that's just the current element that grep tests. All of the files with a byte -size smaller than 1,000 bytes end up in @smaller_than_1000. That array becomes the input for the map, which takes each element and returns it with spaces tacked on the front and a newline on the end.

 #!/usr/bin/perl my @smaller_than_1000 = grep { -s < 1000 } @ARGV; print map { "    $_\n" } @smaller_than_1000; 

Typically we'll do that without the intermediate array, though.

 print map { "    $_\n" } grep { -s < 1000 } @ARGV; 

A.1.2. Exercise 2

We chose to use our home directory as the hardcoded directory. When we call chdir without an argument, it goes to our home directory (so this is one of the few places where Perl doesn't use $_ as the default).

After that, an infinite while loop keeps our code running, at least until we can't satisfy the condition to last that breaks us out of the loop. Look at the condition carefully: we don't just test for truth. What would happen if we wanted to find all the files with a 0 in them? We look for defined values with a nonzero length, so undef (end of input) and the empty string (simply hitting enter) stop the loop.

Once we have our regular expression, we do that same thing we did in the previous answer. This time we use the result of glob as the input list and a pattern match inside the grep. We wrap an eval { } around the pattern match in case the pattern doesn't compile (for instance, it has an unmatched parenthesis or square bracket).

 #!/usr/bin/perl chdir; # go to our home directory while( 1 )         {         print "Please enter a regular expression> ";         chomp( my $regex = <STDIN> );         last unless( defined $regex && length $regex );         print map { "    $_\n" } grep { eval{ /$regex/ } }                 glob( ".* *" );         } 




Intermediate Perl
Intermediate Perl
ISBN: 0596102062
EAN: 2147483647
Year: N/A
Pages: 238

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net