In message <3C074313.2038.6FC2633@localhost>,
"Keith C. Ivey" writes:
: Greg Bacon <[EMAIL PROTECTED]> wrote:
:
: > You have a finite sequence of unknown length, where each
: > element in the sequence is a string. Output the middle
: > element of the sequence (for a reasonable definition of
: > middle), traversing the sequence at most once and without
: > storing the elements in an array.
:
: Okay, you've clarified what the input is like. Now we need
: clarification of what "without storing the elements in an
: array" means.
:
: Does "the elements" mean "all the elements" or "any elements"?
: Does "an array" mean you can store whatever elements you want,
: as long as you don't use a Perl array to do it?
I give up. :-)
Here's my solution (which is similar but less elegant than the one
Ian sent):
#! /usr/local/bin/perl
use warnings;
use strict;
sub usage { "Usage: $0 file\n" }
sub midline {
my $fh = shift;
my $lnum = shift || 1;
my $sub = shift || sub { undef };
my $line = <$fh>;
if (defined $line) {
my $next = sub {
my $n = shift;
if ($n == $lnum) {
return $line;
}
else {
return $sub->($n);
}
};
midline($fh, $lnum+1, $next);
}
else {
$sub->(int $lnum/2);
}
}
die usage unless @ARGV == 1;
my $file = shift;
my $fh;
open $fh, $file or die "$0: open $file: $!\n";
my $mid = midline($fh) || "<undefined>\n";
print $mid;
To answer Vladi: yes, magic is needed, i.e., recursion.
Greg