
rGeoffrey
User
Mar 11, 2001, 10:26 AM
Post #1 of 4
(50117 views)
|
This is part of a program I am writing to play with my website's log files that live in 'logdir'. For right now it will just print the line as is (line 14) but that will change soon. If it helps you to think about the problem (and to answer question 8B), the contents of the directory are logs from two months (2001_01.log and 2001_02.log). There are several questions of varying difficulty so everyone should have a chance to play. But the important questions are 13A and 13B.
1 #!/usr/local/bin/perl 2 3 use strict; 4 5 my $dirname = 'logdir'; 6 7 opendir (DIR, $dirname) or die "could not open dir, $!\n"; 8 my @files = sort map {"$dirname/$_" } grep { !/^\.+$/ } readdir DIR; 9 closedir DIR; 10 11 my $it = make_iterator(@files); 12 13 while (my $line = $it->()) { 14 print $line; 15 } 16 17 sub make_iterator 18 { 19 my (@datafiles) = @_; 20 21 return unless @datafiles; 22 23 my $fh = do { local *FH }; 24 while (@datafiles) { 25 my $file = shift (@datafiles); 26 (open ($fh, $file)) 27 ? last 28 : print STDERR "failed to open $file, $!\n" 29 } 30 31 my $iterator = 32 sub { 33 my $line; 34 return $line if ($line = <$fh>); 35 36 while (@datafiles) { 37 close $fh; 38 my $file = shift (@datafiles); 39 unless (open ($fh, $file)) { 40 print STDERR "failed to open $file, $!\n"; 41 next; 42 } 43 return $line if ($line = <$fh>); 44 } 45 return; 46 }; 47 return $iterator; 48 } And now the questions... Line 8 8A) Why is the grep here? 8B) What ends up in @files when the line is finished? Line 23 23A) What is going on here? Lines 24-29 24A) When it finishes looping, what do will $fh do for us? Lines 31-32, 46-47, and 11 31A) What is the name for this type of structure? 31B) What is being returned? 31C) Why are lines 33-44 allowed to use $fh and @datafiles? Line 34 and 43 34A) What will be returned? Lines 36-42 36A) What will cause this while to do the next and skip to the next datafile? 36B) What will cause the loop to not exit at line 43 and move to the next datafile? And the big picture question. I have jumped through many hoops to make line 13 work, so... Line 13 13A) What does it do? 13B) Why was it worth all the effort? As an attachment to this message you can get the code without the line numbers. -- Sun Sep 9, 2001 - 1:46:40 GMT, a very special second in the epoch. How will you celebrate?
|